我正在使用JButton的Action侦听器来绘制不同的形状.它工作正常,但如何在面板上保留以前绘制的形状?因为按下之前形状的另一个按钮已经消失.
jButton1.setText("Button1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Button2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
s = evt.getActionCommand();
repaint();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
s = evt.getActionCommand();
repaint();
}
Run Code Online (Sandbox Code Playgroud)
.......和paintComponent方法是
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("====>>> " + s);
switch (s) {
case "Button1":
g.drawRoundRect(20,20,40,40,100,200);
break;
case "Button2":
g.drawRect(0, 0, 200, 200);
break;
default:
g.drawOval(40, 40, …Run Code Online (Sandbox Code Playgroud)