按下按钮后在另一个面板内打开另一个面板
Open another panel inside another panel after pressing button
我一直收到一条错误消息,说我没有添加一些方法(执行的操作),但我已经添加了。我无法打开面板 2。
public class panel1 extends JPanel implements ActionListener(){
private panel2 p2=new panel2();
private JButton button;
public panel1(){
button=new JButton("open panel2");
add(button,BorderLayout.BEFORE_FIRST_LINE);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
add(p2);
}
});
}
}
考虑这些变化:
public class panel1 extends JPanel implements ActionListener(){
private panel2 p2=new panel2();
private JButton button;
public panel1(){
button=new JButton("open panel2");
add(button,BorderLayout.BEFORE_FIRST_LINE);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
//Add readability: Where to add?
panel1.this.add(p2);
}
});
}
//THIS HERE makes your panel1 implment ActionListener
@Override
public void actionPerformed(ActionEvent ae) {
}
}
另请注意常见的 Java 命名约定 - Class 名称应以大写字母开头 (Panel1 extends JPanel
)
You can check the below code for replacing jpanel without switching jframe.
contentPanel.removeAll();
contentPanel.repaint();
contentPanel.revalidate();
contentPanel.add(//add your panel here);
contentPanel.repaint();
contentPanel.revalidate();
我一直收到一条错误消息,说我没有添加一些方法(执行的操作),但我已经添加了。我无法打开面板 2。
public class panel1 extends JPanel implements ActionListener(){
private panel2 p2=new panel2();
private JButton button;
public panel1(){
button=new JButton("open panel2");
add(button,BorderLayout.BEFORE_FIRST_LINE);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
add(p2);
}
});
}
}
考虑这些变化:
public class panel1 extends JPanel implements ActionListener(){
private panel2 p2=new panel2();
private JButton button;
public panel1(){
button=new JButton("open panel2");
add(button,BorderLayout.BEFORE_FIRST_LINE);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
//Add readability: Where to add?
panel1.this.add(p2);
}
});
}
//THIS HERE makes your panel1 implment ActionListener
@Override
public void actionPerformed(ActionEvent ae) {
}
}
另请注意常见的 Java 命名约定 - Class 名称应以大写字母开头 (Panel1 extends JPanel
)
You can check the below code for replacing jpanel without switching jframe.
contentPanel.removeAll();
contentPanel.repaint();
contentPanel.revalidate();
contentPanel.add(//add your panel here);
contentPanel.repaint();
contentPanel.revalidate();