我正在使用一个选择工具,并且已经提供了这些解决方案,第一种方法是使用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/