gpt4 book ai didi

java Paint() 自动执行?

转载 作者:行者123 更新时间:2023-12-02 08:06:34 30 4
gpt4 key购买 nike

import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.event.*;
import java.awt.geom.*;
import java.util.*;

public class test extends JFrame implements ActionListener, MouseListener {

private Vector<String> vlist = new Vector<String> ();
private int mouseX, mouseY;
Canvas c = new Canvas();

public test () {
setSize(400,400);
addMouseListener(this);

}

public static void main(String[] args) {


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test frame = new test();
//frame.setBackground(Color.yellow);
frame.setVisible(true);
}
});
}

public void actionPerformed(ActionEvent ae) {

}

@Override
public void paint(Graphics g) {

Shape circle = new Ellipse2D.Float(100f, 100f, 100f, 100f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);

}

public void move() {

}

public void drawCircle(int x, int y) {

}

public void mouseClicked(MouseEvent e) {
repaint();

}

public void mouseExited(MouseEvent e) {

}

public void mousePressed(MouseEvent e) {
this.mouseX=e.getX();
this.mouseY=e.getY();
}

public void mouseReleased(MouseEvent e) {

}

public void mouseEntered(MouseEvent e) {

}
}

我想编写一个测试程序来学习java中的图形编程。运行上面的代码,会自动绘制圆圈。为什么paint()方法会自动执行?我单击鼠标时要创建的圆圈。

最佳答案

向类添加属性。

boolean draw;

包围 paint(...) 中的代码
if (draw) {
// existing code
}

这将使程序仅在 draw 为 true 时才进行绘制。最初,它是假的,所以它不会绘制任何东西。单击鼠标时,值属性 draw 将为 true

public void mouseClicked(MouseEvent e) {
draw = true;
repaint();
}

关于java Paint() 自动执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8074898/

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