我有一个有面板的小程序。在面板中添加了一个按钮,单击该按钮将删除当前面板,并将一个新面板添加到当前小程序中。
但我没有得到想要的输出!!!
我想用来自 ActionListener 的新面板替换当前添加到 Applet 的显示面板。
请指出错误!
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JPanel;
public class Init extends JApplet {
public Display ref;
public NewDisplay ref2;
public class Display extends JPanel implements ActionListener {
public Display() {
initComponents();
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton1.setText("New Game");
add(jButton1);
jButton1.addActionListener(this);
}
public javax.swing.JButton jButton1;
@Override
public void actionPerformed(ActionEvent e) {
String x = e.getActionCommand();
if (x.equals("New Game")) {
System.out.println("clicked");
//ref.setVisible(false);
this.removeAll();
//add(ref2);
add(ref2);
invalidate();
revalidate();
repaint();
}
}
}
public class NewDisplay extends JPanel {
public NewDisplay() {
setSize(800, 600);
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillRect(0, 0, 800, 600);
}
}
@Override
public void init() {
ref = new Display();
ref2 = new NewDisplay();
add(ref);
setSize(800,600);
}
}