【问题标题】:code for simple sketching doesnot work well简单草图的代码不能很好地工作
【发布时间】:2015-03-03 18:13:27
【问题描述】:

我是 java 和 java Graphics 的新手。我为草图编写了一个简单的代码,但效果不佳。当我快速拖动鼠标时,会丢失一些像素。这是我的代码..

package test;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

public class testdraw extends JPanel{
    public int x1;
    public int y1;
    public int x2;
    public int y2;
    public testdraw(){
    addMouseMotionListener(new MouseAdapter() {

        public void mouseDragged(MouseEvent e){
            x2=e.getX();
            y2=e.getY();
            repaint();
            x1=x2;
            y1=y2;

        }


    });

}
    public void paintComponent(Graphics g){

        Graphics2D g2=(Graphics2D)g;
        g2.drawLine(this.x1, this.y1,this.x2,this.y2);;

    }
}   

主类..

package test;

import javax.swing.JFrame;
public class testdrawmain {

    public static void main(String args[]){
        JFrame frame=new JFrame();
        testdraw td=new testdraw();
        frame.add(td);
        frame.setSize(350, 350);
        frame.setVisible(true);

   }

}

谁能告诉我什么是错的。请给我建议。提前致谢。

【问题讨论】:

    标签: java swing graphics


    【解决方案1】:
            x2=e.getX();
            y2=e.getY();
            repaint();
            x1=x2;
            y1=y2;
    

    x1 和 x2 在此之后将是 相同,无论您在哪里调用 repaint() - 不是很有用。

    改为获取鼠标位置之前进行分配。

            x1=x2;
            y1=y2;
            x2=e.getX();
            y2=e.getY();
            repaint();
    

    如果要绘制所有点,则创建一个ArrayList<Point>,在鼠标运动侦听器中添加到列表中,并在paintComponent 中遍历列表。

    还有:

    • paintComponent 应该受到保护,而不是公开。
    • 必须在您自己的覆盖中调用 super 的 paintComponent 方法。
    • 请查看this example

    编辑
    您的评论:

    我的应用程序可以像绘画一样绘制......所以每次拖动鼠标时,开始和结束坐标都会改变

    那么您有两个选择:使用 ArrayList<ArrayList<Point>> 或在 BufferedImage 上绘图并在您的 paintComponent 方法中显示 BufferedImage。

    【讨论】:

    • 我的应用程序可以像绘画一样绘制......所以每次拖动鼠标时,开始和结束坐标都会改变......
    • @sovon:那么你有两个选择:使用ArrayList<ArrayList<Point>> 或在 BufferedImage 上绘图
    猜你喜欢
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2015-09-19
    • 2016-12-08
    相关资源
    最近更新 更多