简体   繁体   中英

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 .

To do so, add this line of code at the end of your init() method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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