我已經寫了這個簡單的Cardlayout示例與Splitpane,Combobox和幾個其他面板包含按鈕和標籤。CardLayout不能正常工作
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class splitpane_test extends JFrame implements ItemListener {
private JPanel contentPane;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
JPanel cards;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
splitpane_test frame = new splitpane_test();
//frame.addComponentToPane(frame.getContentPane());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public splitpane_test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JSplitPane splitPane = new JSplitPane();
contentPane.add(splitPane, BorderLayout.CENTER);
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = {BUTTONPANEL, TEXTPANEL};
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
splitPane.setLeftComponent(comboBoxPane);
//Create the "cards".
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
card1.add(new JButton("Button 2"));
card1.add(new JButton("Button 3"));
JPanel card2 = new JPanel();
card2.add(new JTextField("TextField", 20));
//Create the panel that contains the "cards".
cards = new JPanel();
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
splitPane.setRightComponent(cards);
cards.setLayout(new CardLayout(0, 0));
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
System.out.print("Event Triggered \n");
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, TEXTPANEL);
}
}
我可以看到左側的組合框和右側的其他卡片佈局面板上的分離面板。 當我更改組合框項目沒有正確的大小發生。 爲了驗證iam是否擊中了我使用的System.out.print(「觸發的事件\ n」); 但我已經看到了令人驚奇的是,它的每一個組合框項目變更顯示兩倍,如果調用兩次
Event Triggered Event Triggered
能否請你建議我什麼IAM做錯了,爲什麼事件觸發被擊中兩次。 感謝您的所有時間和幫助。
+1 [SSCCE(http://sscce.org/) 。 – trashgod