简体   繁体   中英

Java Swing change panel when a button is pressed from different class

I am writing a program in Java with Java Swing. I have a class, which is a custom JPanel (my class extends JPanel), which is a log in page. The panel contains a button called "Enter".

When I create my main JFrame, I add the Log in Panel in it. When the button "Enter" is pressed I want to remove the Log In panel and proceed to the next panel.

So how can I make my frame understand when the button "Enter" from the Log In panel is pressed (they are in different classes), so that it proceeds to the next page?

To be able to switch beetween JPanels enclose them in CardLayout:

JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";

//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...

//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);

You should add ActonListener to the "Enter" button:

JButton enterButton = ...
enterButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
              CardLayout cl = (CardLayout)// your reference to the CardLayout here eg. yourJFrame.getContentPane().getLayout();
              cl.show(cards, "The name of panel to show, you gave it with the add operation on cardLayout eg. BUTTONPANEL OR TEXTPANEL");
      }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM