gpt4 book ai didi

Java- repaint() 替代方案

转载 作者:行者123 更新时间:2023-11-29 07:55:45 27 4
gpt4 key购买 nike

这是我在鼠标光标附近绘制椭圆的简单代码。每次我单击时都会重新绘制框架,并且当时只能绘制一个椭圆。我想知道如何使单击时绘制的每个椭圆都停留在框架上。感谢您的每条建议。

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Buffer extends JPanel implements MouseListener{
public static JFrame frame;
public static boolean check;

public void paintComponent(Graphics g){
super.paintComponent(g);
if(check==true){
g.drawOval((int)MouseInfo.getPointerInfo().getLocation().getX(), (int)MouseInfo.getPointerInfo().getLocation().getY(), 10, 10);
}
}

public static void main(String args[]){
Buffer x=new Buffer();
x.setBackground(Color.cyan);

frame=new JFrame();
frame.setSize(500,500);
frame.addMouseListener(x);
frame.add(x);
frame.setVisible(true);
}

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

public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
}

最佳答案

创建代表椭圆的对象的 ArrayList。在 paintComponent 中,绘制列表中的每个椭圆。在鼠标监听器中,向列表中添加一个椭圆。这是一个例子:

public class Buffer extends JPanel implements MouseListener {
...
private List<Ellipse2D> ovals = new ArrayList<Ellipse2D>();

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Ellipse2D oval : ovals)
g2d.draw(oval);
}

public void mouseClicked(MouseEvent e) {
ovals.add(new Ellipse2D.Double(e.getX(), e.getY(), 10, 10);
repaint();
}
}

关于Java- repaint() 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17877284/

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