下面是一个旨在用鼠标书写涂画的程序。希望实现的功能具体是:在面板上按住鼠标左键移动鼠标,就可以绘画,按住右键移动,就可以擦去所画的东西。但是经过运行,程序有错误之处,请指出有可能有错误的语句的标号,然后改正程序,使其能够正确实现预期的功能。 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ScribbleDemo extends JFrame //(1) { Point lineStart=new Point(0,0); ScribbleDemo(){ this.addMouseListener(this); //(2) this.addMouseMotionListener(this);// (3) } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { lineStart.move(e.getX(),e.getY()); //(4) } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { Graphics g=getGraphics(); if (e.isMetaDown()) // if条件分支的组合语句(5) { g.setColor(Color.black); g.drawLine(lineStart.x, lineStart.y,e.getX(), e.getY()); lineStart.move(e.getX(), e.getY()); } else // else组合语句(6) { g.setColor(getBackground()); g.fillOval(e.getX() - (20/2),e.getY() - (20/2), 20, 20); } g.dispose(); //(7) } public void mouseMoved(MouseEvent e) { } public static void main(String[] args) { ScribbleDemo f=new ScribbleDemo(); f.setSize(300,300); f.setVisible(true); } }
时间: 2024-02-17 22:04:35 浏览: 159
有可能有错误的语句是标号(5)和标号(6)。
错误在于缺少了MouseListener和MouseMotionListener接口的实现,并且使用了getGraphics()方法来获取画笔,这会导致图形闪烁和不稳定。应该在类的定义中添加MouseListener和MouseMotionListener接口的实现,并覆盖相应的方法,同时使用双缓冲技术来解决图形闪烁和不稳定的问题。改正后的程序如下所示:
```
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ScribbleDemo extends JFrame implements MouseListener, MouseMotionListener {
Point lineStart=new Point(0,0);
Image offScreenImage = null;
Graphics offScreenGraphics = null;
ScribbleDemo(){
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paint(Graphics g){
if(offScreenImage == null){
offScreenImage = createImage(getWidth(), getHeight());
offScreenGraphics = offScreenImage.getGraphics();
}
offScreenGraphics.setColor(getBackground());
offScreenGraphics.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(offScreenImage, 0, 0, null);
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
lineStart.move(e.getX(),e.getY());
}
public void mouseClicked(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseDragged(MouseEvent e){
if(offScreenGraphics == null){
return;
}
if (e.isMetaDown()) {
offScreenGraphics.setColor(Color.black);
offScreenGraphics.drawLine(lineStart.x, lineStart.y,e.getX(), e.getY());
lineStart.move(e.getX(), e.getY());
}
else {
offScreenGraphics.setColor(getBackground());
offScreenGraphics.fillOval(e.getX() - (20/2),e.getY() - (20/2), 20, 20);
}
repaint();
}
public void mouseMoved(MouseEvent e){
}
public static void main(String[] args){
ScribbleDemo f=new ScribbleDemo();
f.setSize(300,300);
f.setVisible(true);
}
}
```
改正后的程序中,重写了paint方法,使用了双缓冲技术,避免了图形闪烁和不稳定的问题。同时,实现了MouseListener和MouseMotionListener接口,并覆盖了相应的方法,保证了程序的正确性。
阅读全文