我正在尝试借助以下代码在摆动窗口 JFrame Container 上添加和删除面板。如果在构造函数中添加了 JPanel 但未添加运行时,则会添加 JPanel。
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class test extends JFrame implements ActionListener {
test() {
Container cp = this.getContentPane();
JButton b1 = new JButton("add");
JButton b2 = new JButton("remove");
cp.add(b1);
cp.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("add")) {
panel1 frm = new panel1();
cp.add(frm);
}
if (ae.getActionCommand().equals("remove")) {
remove(frm);
}
}
public static void main(String args[]) {
test t1 = new test();
t1.show(true);
}
}
class panel1 extends JPanel {
panel1() {
JButton b1 = new JButton("ok");
add(b1);
}
}