0
我想用CardLayout
創建一個帶參數的JPanel
。我有以下代碼:Java在JFrame中創建cardLayout,構造函數參數爲
public class MainFrame extends JFrame{
private JPanel contentPane;
private CardLayout cardLayout;
private String card;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame("");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame(String card) {
initComponents();
cardLayout = new CardLayout();
if(card.equals("ADMIN")){
contentPane.revalidate();
cardLayout.show(this.contentPane, "ADMIN");
}else if(card.equals("USER")){
contentPane.revalidate();
cardLayout.show(this.contentPane, "USER");
}
}
private void initComponents() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1280, 800);
this.contentPane = new JPanel();
this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
this.contentPane.setLayout(cardLayout);
this.contentPane.add(new PanelOne(), "ADMIN");
this.contentPane.add(new PanelTwo(), "USER");
setContentPane(this.contentPane);
}
但是,如果我運行此代碼我得到一個異常:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
wrong parent for CardLayout
我有什麼做的,解決這個問題?
我已經嘗試在主要方法中更改參數,但沒有任何解決方案。
謝謝你,你救了我的一天 – leonkuehn