我希望applet在用户点击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);
}
}
答案 0 :(得分:2)
使用以下命令替换init和paint方法
public void init() {
initComponents();
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showCircle();
}
});
}
private boolean circleIsVisible = false;
private void showCircle() {
circleIsVisible = true;
repaint();
}
public void paint(Graphics g) {
super.paint(g);
if (circleIsVisible) {
g.setColor(Color.red);
g.fillOval(140, 140, 20, 20);
}
}
当applet首次显示时调用paint方法。因此,在绘制之前,您应检查是否应绘制圆。然后在更改状态时将applet重新绘制为'showCircle'。
希望这有帮助。