在下面的代码中,我想根据位于Panel1和Panel2中的按钮的事件来更改面板 .Panel1 仅包含一个按钮,与 Panel2 相同
public class Window extends JFrame {
public window(){
this.setTitle("CardLayout");
this.setSize(300, 120);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Panel2 p2 = new Panel2();
Panel1 p1 = new Panel1();
this.getContentPane().add(p1);
this.setVisible(true);
p2.getButton2().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Panel1 p1 = new Panel1();
getContentPane().removeAll();
getContentPane().add(p1);
getContentPane().validate();
getContentPane().repaint();
System.out.println("change to panel1");
}
});
p1.getButton1().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Panel2 p2 = new Panel2();
getContentPane().removeAll();
getContentPane().add(p2);
getContentPane().validate();
getContentPane().repaint();
System.out.println("change to panel2");
}
});
} }
最佳答案
您可能正在寻找这个
public class testframe extends JFrame {
private JPanel contentPane;
String panel = "Card with JButtons";
String panel2 = "Card with JTextField";
JPanel cards = new JPanel();
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
/**
* Create the frame.
*/
public testframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
setContentPane(contentPane);
cards = new JPanel(new CardLayout());
card1 = new JPanel();
card2 = new JPanel();
JButton b1 = new JButton("button 1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, panel2);
}
});
card1.add(b1);
JButton b2 = new JButton("button 2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, panel);
}
});
card2.add(b2);
cards.add(card1, panel);
cards.add(card2, panel2);
contentPane.add(cards);
}
如果是这样,这也会有帮助:CardLayout
关于java - 从 JPanel 读取 JFrame 中的 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22228670/