Stuck in one place, most likely I do not see the obvious.
There is an application, by pressing the buttons, the panels should change (it works partially). I want to put the buttons on the SOUTH, but they don’t want it (located at the top), and I don’t understand how to make them do it, please look at the code, it’s very simple, tell me the reason.
In fact, for some reason, it turns out that two sweet and my button buttons go right away, sweet is displayed correctly, as I want, and my button is somewhere at the top, and if you click on sweet, nothing happens (and should change panel), and if you click on my button , then sweet also crawls upward, and at the same time the panels change as it should.
enum ViewState { START_STATE, NEXT_STATE; } @SuppressWarnings("serial") class Panel2 extends JPanel { public Panel2() { JPanel panel2 = new JPanel(); panel2.setPreferredSize(new Dimension(1,40)); add(panel2, BorderLayout.SOUTH); panel2.setLayout(new GridLayout()); JButton button = new JButton("sweet"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MyWindowTest.changeState(ViewState.START_STATE); } }); panel2.add(button); this.add(panel2); } } @SuppressWarnings("serial") class Panel1 extends JPanel { public Panel1() { JPanel panel1 = new JPanel(); panel1.setPreferredSize(new Dimension(1,40)); add(panel1, BorderLayout.SOUTH); panel1.setLayout(new GridLayout()); JButton button = new JButton("my button"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MyWindowTest.changeState(ViewState.NEXT_STATE); } }); panel1.add(button); this.add(panel1); } } class MyWindowTest { private static ViewState viewState; private static JPanel mpanel; private static JPanel panel1; private static JPanel panel2; private static JFrame frame; public MyWindowTest() { frame = new JFrame(); mpanel = new JPanel(); panel1 = new Panel1(); panel2 = new Panel2(); frame.setSize(400, 400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(mpanel); frame.add(panel1, BorderLayout.SOUTH); panel1.setLayout(new GridLayout()); frame.add(panel2, BorderLayout.SOUTH); panel2.setLayout(new GridLayout()); changeState(ViewState.START_STATE); frame.setVisible(true); } public static void changeState(ViewState state) { viewState = state; System.out.println("change state: " + viewState); switch (state) { case START_STATE: mpanel.removeAll(); mpanel.add(panel1); mpanel.revalidate(); mpanel.repaint(); break; case NEXT_STATE: mpanel.removeAll(); mpanel.add(panel2); mpanel.revalidate(); mpanel.repaint(); break; default: System.out.println("UNKNOWN STATE!"); break; } } public static void main(String[] args) { @SuppressWarnings("unused") MyWindowTest n = new MyWindowTest(); } } If there are suggestions for improving the code, I will be happy to hear.