I have btnShowLibrary, which shows the books kept in the library. And then I have a button btnReturn that recreates previous JPanel with the btnShowLibrary among them.
Initializing contentPane:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[124px,grow,fill][124px,grow,fill][124px,grow,fill]", "[30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill]"));
btnShowLibrary:
JButton btnShowLibrary = new JButton("Show Library");
btnShowLibrary.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.add(new ShowLibrary().getPane());
contentPane.updateUI();
}
});
contentPane.add(btnShowLibrary, "cell 1 5");
ShowLibrary contentPane:
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[grow]", "[grow,fill][grow][]"));
btnReturn:
Button btnReturn = new JButton("Return");
btnReturn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.add(new Library().getPane());
contentPane.updateUI();
}
});
contentPane.add(btnReturn, "cell 0 1,alignx center,aligny bottom");
Now for what happens:
First click on the btnShowLibrary
From the pictures you can so how it's "moving" and I have no idea why. Can someone explain why this happens and suggest how to fix it?
An easy way to manage multiple panels is with the CardLayout layout. This layout allows you to show one of a number of panels at a time, making it easy to move from one to the other in a window. Here is a demo with some events passing between the GUI panels and the main "controller". Ideally, the GUI classes would be in their own files. See also https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html.