How to Switch between Panels in CardLayout from ActionListeners in external classes

百般思念 提交于 2019-12-04 19:06:30

The ActionEvent will contain the source object that generated the event. In this case the JButton. So generic code for the ActionListener in your GUI1 class would be something like:

JButton button = (JButton)e.getSource();
JPanel buttonPanel = (JPanel)button.getParent();
JPanel cardLayoutPanel = (JPanel)buttonPanel.getParent();
CardLayout layout = (CardLayout)cardLayoutPanel.getLayout();
layout.show(cardLayoutPanel, "2");

Hope this helps.

package cardlayoutsample;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CardLayoutSample {
    JFrame frame = new JFrame("CardLayout Demo");
    JPanel panelCont = new JPanel();
    JPanel panelFirst = new JPanel();
    JPanel panelSecond = new JPanel();
    JButton btnOne = new JButton("Switch");
    JButton btnTwo = new JButton("Back");

    CardLayout cl = new CardLayout();

    public CardLayoutSample(){
        panelCont.setLayout(cl);

        panelFirst.add(btnOne);
        panelSecond.add(btnTwo);
        panelFirst.setBackground(Color.red);
        panelSecond.setBackground(Color.blue);

        panelCont.add(panelFirst,"1");
        panelCont.add(panelSecond,"2");
        cl.show(panelCont, "1");

        btnOne.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent arg0){
            cl.show(panelCont, "2");
        }
    });

        btnTwo.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent arg0){
            cl.show(panelCont, "1");
        }
    }); 

        frame.add(panelCont);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
    CardLayoutSample a = new CardLayoutSample();
    }
}

Try to play this button you can see it's switching the panels when you clicked the buttons.

Syntax for ActionListener

Component.addActionListener(new ActionListener (){
@Override
  public void actionPerformed(ActionEvent e){
  //do this
 }
});

Example

LogoutButton.addActionListener(new ActionListener (){
@Override
   public void actionPerformed(ActionEvent e){
   System.exit(0);
 }
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!