Reloading JFrame on JMenuItem selection

S

Swetha

Hello all

I have the following classes:
myFrame which implements JFrame,
myMenuBar which implements JMenuBar and
myPanel1 and myPanel2 which implement JPanel.


// class my MenuBar
public class myMenuBar extends javax.swing.JMenuBar implements
java.util.Observer
{
class myListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// I want to be able to access the JFrame of which this is
a part
// myFrame.setContentPane(myPanel2);
}
}

public myMenuBar()
{
createMenuBar();
}

private void createMenuBar()
{
JMenu menu = new JMenu("some menu");
add(menu);

JMenuItem menuItem = new JMenuItem("item1");
menuItem.addActionListener(new myListener());
menu.add(menuItem);
}
}


//class myPanel1
public class myPanel1 extends javax.swing.JPanel implements
java.util.Observer
{
public myPanel1()
{
// Add components to the panel
}
}

//class myPanel2
public class myPanel2 extends javax.swing.JPanel implements
java.util.Observer
{
public myPanel2()
{
// Add components to the panel
}
}


// class myFrame
public class myFrame extends javax.swing.JFrame implements
java.util.Observer
{
public myFrame()
{
createFrame();
}

private void createFrame()
{
// create menubar and assign to frame
menubar = new myMenuBar();
setJMenuBar(menubar);

// initialize panel
setContentPane(new myPanel1());

pack();
setVisible(true);
}
}


So, myFrame instantiates objects of myPanel1 and myMenuBar and sets
them as its ContentPane and JMenuBar respectively. Now, when the user
selects the menu item in my MenuBar, I want to be able to set the
ContentPane of myFrame to myPanel2 in the actionPerformed method of
myMenuBar.

To be able to that I need to access myFrame from myMenuBar.

I tried passing the instance of myFrame to myMenuBar while creating it:
new myMenuBar(this)

but when I try to access myFrame from myMenuBar my application crashes.

Can someone suggest how I can go about accessing myFrame in myMenuBar?

Thanks!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top