gpt4 book ai didi

java - 响应用户输入的 Applet 绘图

转载 作者:行者123 更新时间:2023-11-30 04:23:44 25 4
gpt4 key购买 nike

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


}

最佳答案

将 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”一样重新绘制。

希望这有帮助。

关于java - 响应用户输入的 Applet 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16383990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com