gpt4 book ai didi

java - 使用 getGraphics 进行闪烁绘画

转载 作者:行者123 更新时间:2023-12-02 06:19:28 25 4
gpt4 key购买 nike

我正在做一个选择工具,我已经提供了这些解决方案,在第一个使用 JPanel getGraphics 方法中,我在鼠标拖动的地方绘制一个椭圆形,在第二个中,我重写 PaintComponent 方法来绘制椭圆形。

当我执行第一个方法时,拖动鼠标时会出现闪烁,并且绘图效果很差,而第二种方法则运行完美。为什么会发生这种情况?如果我在第一个解决方案中退出重绘,它会绘制椭圆形并且不会“删除”它们。

执行此类操作的最佳实践是什么?当我使用 getGraphics 绘图时,我是否遗漏了某些内容?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class TestGetGraphics extends JFrame {

JPanel canvas;
Painter painter;

class Painter{
void paint( Graphics2D g, Point p ){
g.drawOval(p.x, p.y, 30, 30);
}
}

public TestGetGraphics(){
super();

canvas = new JPanel();
painter = new Painter();

canvas.setPreferredSize( new Dimension(400, 400) );
canvas.setBackground(Color.WHITE);

canvas.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent me){
painter.paint((Graphics2D) canvas.getGraphics(), me.getPoint());
canvas.repaint();
}
});

add( canvas );

setVisible(true);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}


public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new TestGetGraphics();
}
});
}

}

这是paintComponent方法:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class TestPaintComponent extends JFrame {
JPanel canvas;
Painter painter;

class Painter{
Point p;
void paint( Graphics2D g ){
if( p != null )
g.drawOval(p.x, p.y, 30, 30);
}

void setPoint( Point p ){
this.p = p;
}
}

public TestPaintComponent(){
super();

canvas = new JPanel(){
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
painter.paint((Graphics2D) g);

}

};
painter = new Painter();

canvas.setPreferredSize( new Dimension(400, 400) );
canvas.setBackground(Color.WHITE);

canvas.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent me){
painter.setPoint(me.getPoint());
canvas.repaint();
}
});

add( canvas );

setVisible(true);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}



public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new TestPaintComponent();
}
});
}
}

最佳答案

不要在组件上调用 getGraphics()。相反,扩展组件并重写paintComponent()。更多信息请点击:http://docs.oracle.com/javase/tutorial/uiswing/painting/

关于java - 使用 getGraphics 进行闪烁绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21144633/

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