本文介绍了如何在外部类中的ActionListeners中切换CardLayout中的面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在主类中有一个cardLayout,通过面板将Gui类添加到布局中,当按下Room1Button时,如何将主方法中的卡切换到Gui2卡
I have a cardLayout in the main class that the Gui classes are added to layout via panels and when the Room1Button is pressed how would it switch the card in the main method to the Gui2 card
这是解决此问题的最佳方式。任何帮助都是预先支付的
is this the best way to go about this any help would be apreatiated
主要方法
import javax.swing.*;
import java.awt.*;
class Main
{
CardLayout cl=new CardLayout();
GridBagConstraints gb=new GridBagConstraints();
JFrame frame=new JFrame("Frame");
JPanel panel =new JPanel();
Gui1 g1= Gui1();
Gui2 g2= Gui2();
public Main()
{
panel.setLayout(cl);
panel.add(g1, "1");
panel.add(g2, "2");
frame.add(panel);
frame.pack();
frame.setVisible(true);
cl.show(panel,"1");
//how would the actionlistner in the Gui1 class switch the layout to "2"
cl.show(panel, "2");
}
public static void main(String[]param)
{
new Main();
}
}
gui1类
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Gui1 extends JPanel implements ActionListener{
private JButton room1Button;
JPanel panel=new JPanel();
{
setSize(1000,1000);
panel.setVisible(true);
room1Button=new JButton("Go the next Panel");
this.setVisible(true);
room1Button.addActionListener(this);
add(room1Button);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==room1Button){
Window w = SwingUtilities.getWindowAncestor(R0.this);
w.setVisible(false);
}
}
}
Gui2类
public class Gui2 extends JPanel implements Actionlistener
{
// some code
}
推荐答案
ActionEvent将包含生成事件的源对象。在这种情况下,JButton。因此,GUI1类中ActionListener的通用代码如下所示:
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");
这篇关于如何在外部类中的ActionListeners中切换CardLayout中的面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!