我想使用 .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关于空布局
的观点,但您面临的问题有不同的来源。您不应将组件直接添加到 JScrollPane
中,而应添加到 JScrollPane
的 ViewPort
中。
行 mainScroll.add(container);
应该是 mainScroll.getViewport().add(container);
关于java - JScrollPane 中具有空布局的 JPanel - 看不到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38189140/