我希望小程序在用户点击 jButton1 时绘制一个圆圈,但该圆圈会自发地绘制它,而不是响应用户输入。我尝试了很多方法,我什至在网上搜索了两天的答案,但我找不到一个。这就是我今天所达到的。
package project002;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
/**
*
* @author B_HITMAN
*/
public class NewApplet extends JApplet {
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton1.setText("jButton1");
jButton2.setText("jButton2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jButton1)
.addGap(41, 41, 41)
.addComponent(jButton2)
.addContainerGap(192, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(247, Short.MAX_VALUE))
);
}
public void init() {
initComponents();
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Graphics g = getGraphics();
update(g);
}
});
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(140, 140, 20, 20);
}
}