May'Habit
May'Habit

Reputation: 1372

How to use code to add jpanel to jframe in netbean 8.0.2

I have some code like this:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  

        // create header panel
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BorderLayout(600, 100));
        this.getContentPane().add(hPanel);

        // text header
        JLabel hLabel = new JLabel("LỊCH VẠN NIÊN 2015");
        hPanel.add(hLabel);

    }  

I create a form has with and height are 600px and 400px. I want to add a panel (600x100) include a text has center vertical and center horizontal. I try code above but my frame is blank. Please help me, I'm a newbie :)

Upvotes: 2

Views: 121

Answers (1)

StanislavL
StanislavL

Reputation: 57381

hPanel.setLayout(new BorderLayout(600, 100));

That means gap between compponents is 600 (horizontal) and 100 (vertical). Nothing related to size.

Try setPreferredSize() instead but it's not recommended. It's better to reflect sizes of componnets rather than define your own.

Also move the

this.getContentPane().add(hPanel);

to the method end to be the last statement.

You may also need to call pack() or setSize() of the frame.

Upvotes: 1

Related Questions