Java初学者,请各位帮帮忙

zhuimingwo 2010-03-29 01:18:03
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseDemo2 extends JFrame implements MouseListener, MouseMotionListener
{
int flag;
int x = 0;
int y = 0;
int startx, starty, endx, endy;

public MouseDemo2()
{
Container contentPane = getContentPane();
contentPane.addMouseListener(this);
contentPane.addMouseMotionListener(this);
setSize(300, 300);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void widowClosing(WindowEvent e)
{
System.exit(0);
}});
}

public void mousePressed(MouseEvent e)
{
startx = e.getX();
starty = e.getY();
}

public void mouseReleased(MouseEvent e)
{
endx = e.getX();
endy = e.getY();
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}

public void mouseMoved(MouseEvent e)
{
flag = 1;
x = e.getX();
y = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)
{
flag = 2;
x = e.getX();
y = e.getY();
repaint();
}

public void update(Graphics g)
{
g.setColor(this.getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
paint(g);
}

public void paint(Graphics g)
{
g.setColor(Color.black);
if(flag == 1)
{
g.drawString("鼠标坐标:("+x+", "+y+")", 10, 50);
g.drawLine(startx, starty, endx, endy);
}
if(flag == 2)
{
g.drawString("拖拽鼠标坐标: ("+x+", "+y+")", 10, 50);
g.drawLine(startx, starty, x, y);
}
}

public static void main(String[] args)
{
new MouseDemo2();
}
}
运行老是出问题,直线画不出来,请高手指教啊!
...全文
117 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhuimingwo 2010-03-29
  • 打赏
  • 举报
回复
多谢这位大哥!
doudou 2010-03-29
  • 打赏
  • 举报
回复

//修改一下这两个地方
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g){
g.clearRect(0, 0, getWidth(), getHeight());//清空图像
//......省略
}

62,627

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧