Hello :)
This is my first post. I haven't done a Java type program in a while (2-3 years). I am trying to write a simple program which displays a window with 5 buttons. When you click either the first or second button it should open another window within which stuff will be done by the user ie. text entered etc.
I would like to somehow add "Back" buttons to those new windows so they can return to the original 'menu' with the 5 buttons. I have used 1 JFrame and 'attempted' to use multiple JPanels in order to do this.
An expert programmer from another java forum has said it is important to use just one JFrame and play with JPanels rather than using many different JFrames. Is this true? I dont know. Here is my program. Please feel free to criticize my poor coding practise as I have forgotten how to play with constructors and classes to do my dirty work :) Also, I have used the validate() and removeAll() methods in order to somehow manipulate Containers and start new windows but Im stuck now :( I dont know how to add the "back" buttons.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MyProgram {
public static void main(String args[]) {
final JFrame myJFrame = new JFrame("Tax Program");
final JPanel panel = new JPanel();
final Container cp = myJFrame.getContentPane();
JButton button1 = new JButton("First window");
JButton button2 = new JButton("Second window");
JButton button3 = new JButton("button 3");
JButton button4 = new JButton("button 4");
JButton button5 = new JButton("button 5");
panel.setLayout(new GridLayout(5,1));
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//myJFrame.setVisible(false);
cp.removeAll();
myJFrame.setSize(700,400);
JPanel Panel1 = new JPanel();
cp.add(Panel1);
cp.validate();
}
};
ActionListener al_2 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
cp.removeAll();
myJFrame.setSize(700,600);
JPanel Panel2 = new JPanel();
cp.add(Panel2);
cp.validate();
}
};
button1.addActionListener(al);
button2.addActionListener(al_2);
cp.add(panel);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
myJFrame.setSize(600,600);
//Puts the window in the middle of the screen.
myJFrame.setLocationRelativeTo(null);
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myJFrame.setVisible(true);
}
}