1

我希望小程序在用户点击 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);
}


}
4

1 回答 1

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);
    }
}

小程序首次显示时调用paint 方法。因此,您在绘制圆之前检查是否应该绘制圆。然后当状态改变时让小程序重绘为'showCircle'。

希望这可以帮助。

于 2013-05-05T11:48:22.757 回答