在网上我读到要将组件添加到JscrollPane,我们必须执行:
scrollPane.getViewport().setView(jpanel);
嗯,这是我的代码。为了显示多个组件,在本例中是JButtons,我试图将它们添加到多个JPanel中,并在最后按顺序添加它们。但只显示了最后一个JPanel。为什么呢?
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import layout.TableLayout;
public class Main {
public static void main(String argv[]) {
JFrame jframe = new JFrame("Protocollo UTL");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(1200, 450);
JPanel body = new JPanel();
double[][] size = {
{0.05},
{0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}
};
body.setLayout(new TableLayout(size));
for(int i=0; i<19; i++) {
body.add(new JButton(String.valueOf(i)), "0,"+String.valueOf(i));
}
JPanel body2 = new JPanel();
body2.setLayout(new TableLayout(size));
for(int j=0; j<6; j++) {
body2.add(new JButton(String.valueOf(j)), "0,"+String.valueOf(j));
}
JScrollPane scrollPane = new JScrollPane(body,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.getViewport().setView(body);
scrollPane.getViewport().setView(body2);
jframe.add(scrollPane);
jframe.setVisible(true);
}
}
答案 0 :(得分:2)
你用第二个陈述覆盖了第一个陈述
scrollPane.getViewport().setView(body);
scrollPane.getViewport().setView(body2);
您应该将JPanel
添加到某个父组件,并将该组件设置为视图。像这样:
Container cont = new Container();
cont.add(body);
cont.add(body2);
scrollPane.getViewport().setView(cont);
修改强>
我认为你根本不需要那条线(setView(...)
)。试试这个(把它放在最后四行)
Container cont = new Container();
cont.add(scrollPane);
cont.add(body2);
cont.setLayout(new GridLayout());
jframe.add(cont);
jframe.setVisible(true);