java 如何让以下代码画图流畅,而不是断断续续,因双缓冲没学,尽量在以下代码基础上该把,求大师指点
发布网友
发布时间:2022-04-23 10:31
我来回答
共1个回答
热心网友
时间:2023-10-11 13:05
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawDemo extends JFrame
{
private Container c;
private JLabel label;
private MyPaint myPaint;
public DrawDemo()
{
super("草稿面板");
label = new JLabel("草稿面板", JLabel.CENTER); // 文本居中
c = getContentPane();
myPaint = new MyPaint();
label.setFont(new Font("Serif", Font.BOLD, 22)); // 设置组件文字大小
c.setLayout(new BorderLayout());
c.add(label, BorderLayout.NORTH);
c.add(myPaint, BorderLayout.CENTER);
setBounds(200, 200, 500, 500);
setVisible(true);
}
public static void main(String args[])
{
DrawDemo app = new DrawDemo();
}
}
class MyPaint extends JPanel
{
private int x = 0, y = 0;
private int nx = 0, ny = 0;
private Point startPoint = new Point(x, y);
private Point endPoint = new Point(nx, ny);
public MyPaint()
{
addMouseMotionListener(new MyMouseMotionListener());
addMouseListener(new MyMouseListener());
}
public void paint(Graphics g)
{
g.drawLine((int) startPoint.getX(), (int) startPoint.getY(), (int) endPoint.getX(), (int) endPoint.getY());
startPoint = endPoint;
}
// 拖拽侦听
class MyMouseMotionListener extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent e)
{
endPoint = e.getPoint();
repaint();
}
public void mouseMoved(MouseEvent e)
{
endPoint = e.getPoint();
}
}
// 鼠标单击侦听
class MyMouseListener extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
startPoint = e.getPoint();
}
}
}