Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Separate Panels

Status
Not open for further replies.
May 29, 2003
1
US
I would like to know the class structure and/or code to create a frame, initialized to a panel with a button. Clicking this button then takes you to a separate panel which also has a button, which goes back to the previous panel. Basically, to use as a simple menu system.

A simple concept, yet one I'm finding hard to get to work in code. I just haven't grasped the how the events and calling of the classes interact entirely. I'm sure I'm close, but a little help would be grateful.

Thanks,

Jeff
 
Try this:

import java.awt.event.*;
import javax.swing.*;

class Test extends JFrame implements ActionListener {
JButton button1=new JButton("Show panel 2");
JButton button2=new JButton("Show panel 1");
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();

public Test() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
button1.addActionListener(this);
button2.addActionListener(this);
panel1.add(button1);
panel2.add(button2);
getContentPane().add("Center", panel1);
setSize(200,200);
setTitle("Panel 1");
setVisible(true);
}

public void actionPerformed(ActionEvent e) {
if(e.getSource()==button1) {
getContentPane().remove(panel1);
getContentPane().add(panel2);
getContentPane().validate();
setTitle("Panel 2");
repaint();
}
if(e.getSource()==button2) {
getContentPane().remove(panel2);
getContentPane().add(panel1);
getContentPane().validate();
setTitle("Panel 1");
repaint();
}
}

public static void main(String s[]) {
new Test();
}
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top