我想用.setLocation(x, y)
设置每个元素的位置
我需要JScrollPane
中的JPanel
。但是当我将组件添加到JPanel
时,只显示按钮。但不是JLabel
。
下面的方法在JFrame
构造函数中调用:
private void initGUI_test() {
this.setSize(950, 700);
this.setResizable(false);
this.getContentPane().setLayout(null);
JScrollPane mainScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JPanel container = new JPanel();
mainScroll.setSize(900,500);
mainScroll.setLocation(0,100);
mainScroll.setBorder(BorderFactory.createLineBorder(Color.blue));
mainScroll.add(container);
container.setLayout(null);
container.setLocation(0, 0);
container.setSize(900, 500);
JLabel rowA = new JLabel();
rowA.setSize(180, 26);
rowA.setLocation(10, 100);
rowA.setText("Row A");
JButton loadButton = new JButton();
loadButton.setSize(180, 34);
loadButton.setLocation(290, 110);
loadButton.setText("Load file");
container.add(rowA);
container.add(loadButton);
this.getContentPane().add(mainScroll);
}
虽然我完全同意@Frakcool关于null layout
的观点,但你面临的问题有不同的来源。您不应该将组件直接添加到JScrollPane
中,而应该添加到JScrollPane
的ViewPort
中。
mainScroll.add(container);
行应该是mainScroll.getViewport().add(container);