R
R
Redry2018-07-20 15:17:19
Java
Redry, 2018-07-20 15:17:19

How to implement switching between panels in java?

I'm trying to make an application that opens one page when launched, and when a button is clicked, it switches to another page.
Main class:

public class Main {
  public static Frame frame;
  public static JPanel[] panels = {new Panel(), new myAction()};
  public static int panelNumber = 0;
    
  public static void main(String[] args) {					
    frame = new Frame();
    frame.add(panels[panelNumber]);
  }
}

Panel class:
class Panel extends JPanel {			
  public Panel() {
    JButton btn = new JButton("Start");
    add(btn);
    btn.addActionListener(new ActionListener() {			
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        Main.panelNumber = 1;				
      }
    });
  }	
}

Different pages represent different panels. The class of the second panel is the same, only when you click on the button, panelNumber switches back to 0. The problem is that there is no switching between them. Although if you manually change the panelNumber in the Main class, then only the second panel will be displayed at startup. How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxLich, 2018-07-23
@MaxLich

Either manipulate the visibility of panels, or create/delete panels (maybe here you will need methods repaint()andrevalidate()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question