java 鼠标绘图的问题

用java编一个小的程序,用鼠标在JPanel上面画图,但是有点问题,求解决packagecom.china.herbert;importjava.awt.Color;i... 用java编一个小的程序,用鼠标在JPanel上面画图,但是有点问题,求解决
package com.china.herbert;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;

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

/*
* @ author HerbertChina
* @ version v1.0.0
* Here is the entrance of the program.
*/
public class ScreenPen
{
public static void main(String[] args)
{
ScreenPenFrame frame = new ScreenPenFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

/*
* A frame with a panel for SreenPen
*/
class ScreenPenFrame extends JFrame
{
private static final long serialVersionUID = -1487612798645729975L;
private static final int DEFAULT_Y = 300;
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 300;
private static final int DEFAULT_X = 400;
public ScreenPenFrame()
{
setTitle("ScreenPen");
setBounds(DEFAULT_X, DEFAULT_Y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
ScreenPenPanel panel = new ScreenPenPanel();
add(panel);
}
}

/*
* A frame with a panel for SreenPen
*/
class ScreenPenPanel extends JPanel
{
private static final long serialVersionUID = 7353647790994426414L;
private static BufferedImage bi = new BufferedImage(ScreenPenFrame.DEFAULT_WIDTH,ScreenPenFrame.DEFAULT_HEIGHT,BufferedImage.TYPE_INT_ARGB);
private static final Color COLOR_PEN = new Color(255,0,0);
private static final int rgb = COLOR_PEN.getRGB();
public ScreenPenPanel()
{
MouseMotionHandler mouselistener = new MouseMotionHandler();
this.addMouseMotionListener(mouselistener);
setFocusable(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
public void drawing(double x,double y)
{
bi.setRGB((int)x, (int)y, rgb);
if(((int)x-1>0)&&((int)x-1<bi.getWidth()))
bi.setRGB((int)x-1, (int)y, rgb);
if(((int)y-1>0)&&((int)y-1<bi.getHeight()))
bi.setRGB((int)x, (int)y-1, rgb);
if(((int)x-1>0)&&((int)x-1<bi.getWidth())&&((int)y-1>0)&&((int)y-1<bi.getHeight()))
bi.setRGB((int)x-1, (int)y-1, rgb);
repaint();
}
public class MouseMotionHandler implements MouseMotionListener
{
@Override
public void mouseDragged(MouseEvent e)
{
double _x = e.getX();
double _y = e.getY();
if(_x>0 && _x<bi.getWidth()&&_y>0 && _y<bi.getHeight() )
drawing(_x,_y);
}
@Override
public void mouseMoved(MouseEvent e){}
}
}
就是这样,画快了线就不连贯,如何画线快,也能画出连贯的线条啊
我把线调粗也不行
如上面的public void drawing(double x,double y)中的代码
展开
 我来答
Irreappearable
2012-05-12 · TA获得超过4956个赞
知道大有可为答主
回答量:1423
采纳率:25%
帮助的人:3132万
展开全部
这是因为你的drawing方法只是设置像素的颜色值,而移动快速的时候,鼠标事件不会在每个经过的像素上触发事件。

你需要记录上一下鼠标移动事件的坐标,然后在上一次坐标和这一次的坐标之间用Graphics的drawLine方法画直线
追问
你好啊,我按照你的方法做了
但是这样的话,线就不能变粗了,怎么样设置线的粗度啊!
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式