java - JScrollPane 中具有空布局的 JPanel - 看不到元素

标签 java swing jpanel jscrollpane null-layout-manager

我想使用 .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 中,而应添加到 JScrollPaneViewPort 中。

mainScroll.add(container); 应该是 mainScroll.getViewport().add(container);

关于java - JScrollPane 中具有空布局的 JPanel - 看不到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38189140/

相关文章:

java - 使用 MS Access 的 PepareStatement,其中某些值来自不同的表

java - JComboBox 选择的索引更改用于使用按钮单击事件将不同的 JTextField 值发送到 JTable

python GUI 与 Swing 相比?

java - JComboBox 下拉列表中的 JPanel 但不在编辑器中

java - 尝试使用 JFrame 和 JPanel 将窗口绘制为黑色

java - 将依赖项注入(inject)实用程序类映射

java - 在 AWS 上部署带有 H2 数据库的 Spring Boot 应用程序

java - FileUtils.moveDirectory(src,dst) 在目录之间移动文件是否安全

JAVA布局情况

java - JPanel 没有显示在 JFrame 中?