When adding a custom JPanel to my JFrame nothing appears

327 Views Asked by At

I am doing my first Java Swing app, I am using Windows Builder for this.

I have a MainFrame that extends JFrame.

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

    }

Then I have in another class my 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);
        }
    }

I don't get it, the panel works fine in Windows Builder but once I add it, nothing appears, there is already a layout in the JFrame so I don't know what is missing.

Thank you.

1

There are 1 best solutions below

1
On

The problem is that it does not work when you add the element after making it visible with frame.setVisible(true); .

Code should be like this:

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

frame.setVisible(true);

Thanks!.