我正在使用 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();
}
.......而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, 100, 100);
这里 String 包含按下按钮的标题。