我正在努力研究如何在多个摇摆面板之间导航。我想使用CardLayout来完成这项工作,而不是使用玻璃板,因为从我所读到的内容来看,这似乎是这项工作的正确工具(但是,如果你知道其他情况,请随时纠正我)。我写了一个测试用例,它几乎实现了这一点,但在两个方面都有所欠缺。它使用贬值的"show()"方法,此外,在切换到第二张卡后,卡1中的按钮开始神秘地再次浮到表面!
public class test extends JPanel implements ActionListener{
final static int extraWindowWidth = 100;
JButton jbtnOne = new JButton("Button 1");
JPanel cardPanel = new JPanel(new CardLayout());
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
public void addComponentToPane(Container pane) {
//Create the "cards".
JPanel card1 = new JPanel() {
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += extraWindowWidth;
return size;
}
};
card1.add(jbtnOne);
card1.add(new JButton("Button 2"));
card1.add(new JButton("Button 3"));
card2.add(new JTextField("TextField", 20));
cardPanel.add(card1, "card1");
cardPanel.add(card2, "card2");
pane.add(cardPanel, BorderLayout.CENTER);
jbtnOne.addActionListener(this);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TabDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
test demo = new test();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == jbtnOne){
System.out.println("HERE");
card2.show();
}
}
}
CardLayout
正在管理组件,因此您需要在CardLayout
上调用show
,而不是JPanel#show
:
CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
cardLayout.show(cardPanel, "card2");
或者,在切换卡组件时,您也可以使用
cardLayout.next(cardPanel);