I want to create a GUI that allows me to change through different frames. I have a main frame where there are multiple buttons and when clicking on the button, I want to open a new page (like a "display PDF" button). When closing the page created by the button, I want to go back to main frame.
I made a code with creation of different Jframe, and it works as I want, but I would like to know if there is a better and simpler way to do this.
public class MultiplePanelsExample {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton[] buttons;
public MultiplePanelsExample() {
// Step 1: Create the main frame and panel
mainFrame = new JFrame("Main Panel");
mainPanel = new JPanel();
// Step 2: Create an array of buttons
buttons = new JButton[3]; // Adjust the number based on how many buttons you need
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("Open Panel " + (i + 1));
mainPanel.add(buttons[i]);
}
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setVisible(true);
// Step 3: Add action listeners to the buttons
for (int i = 0; i < buttons.length; i++) {
final int buttonIndex = i;
buttons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSecondaryPanel(buttonIndex);
mainFrame.setVisible(false);
}
});
}
}
private void openSecondaryPanel(int buttonIndex) {
// Step 4: Create the secondary frame and panel
JFrame secondaryFrame = new JFrame("Panel " + (buttonIndex + 1));
JPanel secondaryPanel = new JPanel();
JTextArea tx = new JTextArea("Name ");
secondaryPanel.add(tx);
secondaryFrame.add(secondaryPanel);
secondaryFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
secondaryFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// NOW we change it to dispose on close..
secondaryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondaryFrame.setVisible(false);
secondaryFrame.dispose();
mainFrame.setVisible(true);
}
});
secondaryFrame.setVisible(true);
secondaryFrame.pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MultiplePanelsExample();
}
});
}
}