Bernard
Bernard

Reputation: 4580

How to assign a JPanel to JFrame in netbeans gui editor?

I have a JFrame with JMenuBar at the top.

I put a JPanel on my JFrame in the middle and call it Panel1.

Next I create another class called Panel2 extended JPanel and I put some items on that.

Now on my JFrame when user chose one of the JMenuItem I want to assign Panel1 to Panel2 class which I created. Therefore I can see other panel in my JFrame somehow!

How can I do that?

In the class JFrame I have written:

JPanel Panel2 = new JPanel();
Panel1 = Panel2;

It's not working, any suggestion?

Upvotes: 2

Views: 946

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

Several things.

A first remark. Better name the fields, methods, variables with an initial small letter. Very wide convention.

In the GUI editor for panel2 select "Custom creation code" and there you could type new Panel2().

To dynamically exchange a JPanel panel1 with a Panel2 panel2, overwriting the variables would have no effect; the object of panel1 was added to some swing Container of the JFrame.

Do in the action handling of the menu item:

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        remove(panel1);
        panel1 = new Panel2();
        add(panel1);
        invalidate();
    }
});

Seldom done in praxis however.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109815

  • JPanel has FlowLayout as default LayoutManager, implemented in API

  • empty JPanel returns zero PreferredSize

  • you can't add one JPanel to another by Panel1 = Panel2;, then second JPanel isn't added to 1st. JPanel, is required to myPanel1.add(myPanel2)

  • carrefully with reserved Java words and methods names Panel is java.awt.Panel

  • all important informations is in Oracle tutorials A Visual Guide to Layout Managers, How to Use Panels and JPanel API

Upvotes: 2

Related Questions