我是Java新手,我正在通過Swing中的CardLayout
進行導航。基本上我有一個JFrame
上的兩個按鈕,當我點擊一個按鈕,它應該去卡1,我已經在JPanel
,card1
上保持兩個按鈕,當我點擊另一個按鈕時,它應該去卡2,我已經保存了JTextField
面板card2
。但它沒有發生。JPanel on CardLayout Swing Java
任何人都可以修復它嗎?
我的代碼如下。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardLayoutTest extends JFrame implements ActionListener {
JFrame f;
JButton b;
JButton c;
JPanel panel;
JPanel cards;
JPanel card1;
JPanel card2;
CardLayout card;
Container pane;
final String card1Text = "One";
final String card2Text = "Two";
CardLayoutTest() {
}
public void passBtn() {
f=new JFrame("Card Layout Test");
card1 = new JPanel();
card1.add(new JButton("Button 1 - Card 1"));
card1.add(new JButton("Button 2 - Card 1"));
card1.setBackground(new Color(255,0,0));
card2 = new JPanel();
card2.add(new JTextField("TextField on Card 2", 20));
card2.setBackground(new Color(0,255,0));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, card1Text);
cards.add(card2, card2Text);
b = new JButton("Page 1");
b.setBounds(50,50,70,30);
b.setBackground(Color.red);
c = new JButton("Page 2");
c.setBounds(50,80,70,30);
c.setBackground(Color.blue);
pane = f.getContentPane();
pane.add(cards, BorderLayout.CENTER);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
card.show(card1, card1Text);
}
});
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
card.show(card2, card2Text);
}
});
f.add(b); f.add(c); f.add(panel); f.add(cards);
}
public static void main(String[] args) {
new CardLayoutTest();
}
}
你看看這裏:HTT PS://docs.oracle.com/javase/tutorial/uiswing/layout/card.html? – XtremeBaumer
由於你從不初始化'card',我假設你正在得到NullPointerExceptions。你也永遠不會在任何地方使用'卡'。 – VGR