所以我想要一個在選單頁面和主應用程式頁面之間切換的 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();
}
}
uj5u.com熱心網友回復:
您不能將Frames添加到另一個組件。Frame是具有本機對等體的頂級組件。你應該從別的東西(JPanel?)子類化
另外,順便說一句,你在做什么不是好的設計。通常,在 MVC Swing 設計中,所有的視圖和控制方面都應該在一個類中。不要將視圖分成多個類,除非這些類中的每一個都作為自己的可重用小部件
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402527.html
標籤:
