【问题标题】:When adding a custom JPanel to my JFrame nothing appears将自定义 JPanel 添加到我的 JFrame 时,什么也没有出现
【发布时间】:2017-07-24 08:36:50
【问题描述】:

我正在做我的第一个 Java Swing 应用程序,为此我正在使用 Windows Builder。

我有一个扩展 JFrame 的 MainFrame。

public class MainFrame extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);


                    PanelTest panelTest = new PanelTest();
                    frame.getContentPane().add(panelTest);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MainFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
    }

    }

然后我在另一个班级有我的JPanel

package gui;

public class PanelTest extends JPanel {

    /**
     * Create the panel.
     */
    public PanelTest() {

        setBounds(100, 100, 1225, 835);
        //getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        //getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(null);
        {
            JLabel lblCreacion = new JLabel("Hello");
            lblCreacion.setBounds(180, 16, 427, 20);
            contentPanel.add(lblCreacion);
        }
    }

我不明白,该面板在 Windows Builder 中工作正常,但是一旦我添加它,什么都没有出现,JFrame 中已经有一个布局,所以我不知道缺少什么。

谢谢。

【问题讨论】:

  • 在调用setVisible之前添加它,向可见的GUI添加元素需要更多技巧来告诉UI已经更新。
  • 在 GUI 配置完成后始终调用frame.setVisible(true);
  • 您在哪里将PanelText 实例添加到JFrame

标签: java swing windowsbuilder


【解决方案1】:

问题是在使用 frame.setVisible(true); 使其可见后添加元素时它不起作用.

代码应该是这样的:

PanelTest panelTest = new PanelTest();
frame.getContentPane().add(panelTest);

frame.setVisible(true);

谢谢!

【讨论】:

  • “问题是当你添加元素使其可见后它不起作用” - 你可以只用revalidaterepaint 来更新UI 可见后,但一般来说,您希望构建 UI 然后显示它,因为它通常更容易
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 1970-01-01
相关资源
最近更新 更多