我正在尝试解决如何在摇摆中浏览多个面板。我想通过使用 CardLayout 而不是使用玻璃面板来做到这一点,因为从我读过的内容来看,这似乎是这项工作的正确工具(但是,如果您不知道,请随时纠正我)。我写了一个测试用例,它几乎实现了这一点,但在两个方面都达不到要求。它使用了已弃用的“show()”方法,而且在切换到第二张卡片后,card1 中的按钮又开始神秘地浮出水面!
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();
}
}
}