所以我想要一个在菜单页面和主应用程序页面之间切换的 CardLayout 类,但我想在它们自己的类中设计这两个面板,然后在不同的类中添加 ActionListener 和 CardLayout ,并让 ActionListener 使用在面板类之一中创建的按钮。
这是一个(不太短的)SSCCE,涵盖了我想说的内容:
import java.awt.*;
import javax.swing.*;
public class MenuPanel extends Frame{
JPanel menuPanel;
JButton login;
JButton signup;
public MenuPanel(){
menuPanel = new JPanel(new GridBagLayout());
login = new JButton("Login");
signup = new JButton("Signup");
menuPanel.add(login);
menuPanel.add(signup);
}
}
import java.awt.*;
import javax.swing.*;
public class MainPanel extends JFrame{
JPanel menuPanel;
JButton login;
JButton signup;
public MainPanel(){
mainPanel = new JPanel(new GridBagLayout());=
menuPanel.setBackground(Color.grey);
}
}
import java.awt.*;
import javax.swing.*;
public class CardLayout extends Frame implements ActionL {
//Now how do I add the frames from the other classes so that I can add them to my CardLayout?
CardLayout cl = new CardLayout();
JPanel panelCont;
public CardLayout() {
frame.add(panelCont);
panelCont = new JPanel(cl);
//Here is where I'm having trouble
panelCont.add(menuPanel, "1");
panelCont.add(mainPanel, "2");
cl.show(panelCont, "1");
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(panelCont, "2");
}
});
}
}
public class Main {
public static void main(String[] args) {
new CardLayout();
}
}
您无法添加Frame
s 到另一个组件。Frame
是具有本机对等点的顶级组件。你应该从其他东西(JPanel?)继承
另外,顺便说一句,你所做的并不是好的设计。一般来说,在 MVC Swing 设计中,所有视图和控制方面都应该位于一个类中。不要将视图拆分为多个类,除非每个类都作为其自己的可重用小部件
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)