面板不显示任何内容

问题描述

我有下面的代码,假设显示一些文本,但它没有,我找不到原因。

public class TestMLD extends JPanel{
    
    TestMLD(){
        init();
    }
    
    private void init() {
        FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
        Font font = new Font(Font.MONOSPACED,Font.ITALIC,100);
        JLabel helloLabel = new JLabel("Hello World !");
        helloLabel.setFont(font);
        helloLabel.setForeground(Color.BLUE);
    }


    public static void main(String[] args) {

        JFrame frame = new JFrame();
          frame.getContentPane().add(new TestMLD());
          frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400,400);
          frame.setVisible(true);
          new TestMLD();
    }

}

提前致谢

解决方法

这里的问题是您实际上从未将 JLabel helloLabel 添加到您的 JPanel / TestMLD

为此,请在 init() 方法的末尾添加以下代码行:

add(helloLabel);

您实际上也从未将您创建的布局设置到面板

setLayout(flow);

此外,第二次创建 new TestMLD() 对象是多余的。你可以省略那个。

总的来说,更新后的代码应该是这样的:

public class TestMLD extends JPanel {
    
    TestMLD() {
        init();
    }
    
    private void init() {
        FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
        setLayout(flow);
        Font font = new Font(Font.MONOSPACED,Font.ITALIC,100);
        JLabel helloLabel = new JLabel("Hello World !");
        helloLabel.setFont(font);
        helloLabel.setForeground(Color.BLUE);
        add(helloLabel);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new TestMLD());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400); 
        frame.setVisible(true);
    }
}