java swing 平滑移动,Java Swing通过鼠标单击和拖动绘制线条

I want to bring back a question that was asked before: java draw line as the mouse is moved

"I would like to add a feature to my application which allows the user to draw a straight line by clicking the mouse at the start location and releasing it at the end location. The line should move as the mouse moves until it is finally released; similar to the way that a line can be drawn using the Microsoft Paint application.

How can implement this so that the line is repainted as it moves without repainting other things that may already be drawn in that rectangular area?"

Question is: How can I draw multiple lines with the old lines still there?

This is the code that works for me, but the previous line gets erased as soon as you draw a new one:

public static void main(String args[]) throws Exception {

JFrame f = new JFrame("Draw a Red Line");

f.setSize(300, 300);

f.setLocation(300, 300);

f.setResizable(false);

JPanel p = new JPanel() {

Point pointStart = null;

Point pointEnd = null;

{

addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

pointStart = e.getPoint();

}

public void mouseReleased(MouseEvent e) {

pointStart = null;

}

});

addMouseMotionListener(new MouseMotionAdapter() {

public void mouseMoved(MouseEvent e) {

pointEnd = e.getPoint();

}

public void mouseDragged(MouseEvent e) {

pointEnd = e.getPoint();

repaint();

}

});

}

public void paint(Graphics g) {

super.paint(g);

if (pointStart != null) {

g.setColor(Color.RED);

g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);

}

}

};

f.add(p);

f.setVisible(true);

}

解决方案

This is the code that works for me, but the previous line gets erased as soon as you draw a new one:

There are two common approaches:

Keep an ArrayList of objects to paint. Then the paintComponent() method repaints all the objects each time the component needs to repaint itself

Paint onto a BufferImage and then just paint the BufferedImage.

Check out Custom Painting Approaches for a working example of both of these approaches.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值