简体   繁体   English

面板不显示任何内容

[英]Panel doesn't display anything

I have this code bellow that is suppose to display some text but it don't and I can't find the reason why.我有下面这段代码,它假设显示一些文本,但它没有,我找不到原因。

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();
    }

}

Thanks in advance提前致谢

The issue here is that you never actually add the JLabel helloLabel to your JPanel / TestMLD .这里的问题是您实际上从未将JLabel helloLabel添加到您的JPanel / TestMLD中。

To do so, add this line of code at the end of your init() method:为此,请在init()方法的末尾添加这行代码:

add(helloLabel);

You also never actually set the layout you created to your panel您也从未真正将您创建的布局设置为面板

setLayout(flow);

Also, the second time you create a new TestMLD() object is redundant.此外,第二次创建new TestMLD() object 是多余的。 You can omit that.你可以省略它。

All together, the updated code should look something like this:总之,更新后的代码应如下所示:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM