0

我的问题在Java Challenge on Permitting the User to Draw A Line中有所提及,但是,我仍然遇到困难,因为单击并拖动鼠标时我的应用程序上没有出现任何线条。

回答这个问题肯定会帮助大多数初学者更好地理解图形类和绘图,这是一个通常复杂的过程,尤其是对于初学者。

根据我正在使用的文本(因为我正在自己学习 Java),这是如何使用 Java 画线的示例:

/*
 * LineTest
 * Demonstrates drawing lines
 */

import java.awt.*;
public class LineTest extends Canvas {

public LineTest() {
    super();
    setSize(300, 200);
    setBackground(Color.white);
}

public static void main(String args[]) {
    LineTest lt = new LineTest();
    GUIFrame frame = new GUIFrame("Line Test");
    frame.add(lt);
    frame.pack();
    frame.setVisible(true);
}

public void paint(Graphics g) {
    g.drawLine(10, 10, 50, 100);
    g.setColor(Color.blue);
    g.drawLine(60, 110, 275, 50);
    g.setColor(Color.red);
    g.drawLine(50, 50, 300, 200);
}
}

规范是:

Create an application that allows you to draw lines by clicking the initial 
point and draggingthe mouse to the second point. The application should be 
repainted so that you can see the line changing size and position as you
are dragging the mouse. When the mouse button is eleased, the line is drawn.

正如您将认识到的,运行此程序不会由用户创建任何图形。我相信由于缺少 mouseReleased 方法而遇到此错误。

任何帮助是极大的赞赏。预先感谢您在此问题上的所有时间和合作。

我回答这个问题的代码是:

import java.awt.*;
import java.awt.event.*;

public class LineDrawer2 extends Canvas {

    int x1, y1, x2, y2;

      public LineDrawer2() {
          super();
    setSize(300,200);
    setBackground(Color.white);
      }

public void mousePressed(MouseEvent me) {
          int x1 = me.getX();
    int y1 = me.getY();
          x2 = x1;
    y2 = y1;
    repaint();
}

      public void mouseDragged(MouseEvent me) {
    int x2 = me.getX();
    int y2 = me.getY();
    repaint();
}

public void mouseReleased(MouseEvent me) {
}

      public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.blue);
          g.drawLine(x1, y1, x2, y2);
}

public static void main(String args[]) {
    LineDrawer2 ld2 = new LineDrawer2();
    GUIFrame frame = new GUIFrame("Line Drawer");
    frame.add(ld2);
    frame.pack();
    frame.setVisible(true);
}

public void mouseMoved(MouseEvent me) {
}
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}

}

PS:我从上一个回复中了解到这是一个旧格式,但是,如果可能的话,请告诉我使用旧格式,我一定会学习新的。我真诚地感谢它。

4

1 回答 1

1

您正在初始化局部变量,而不是在事件处理方法中初始化字段。代替

int x2 = me.getX();
int y2 = me.getY();

它应该是

this.x2 = me.getX();
this.y2 = me.getY();

或者干脆

x2 = me.getX();
y2 = me.getY();

编辑:

另一个问题是,即使你的类有mousePressed()、mouseDragged() 等方法,它也没有实现MouseListener 和MouseMotionListener。最后,它不会给自己添加任何这样的监听器。所以代码应该修改如下:

public class LineDrawer2 extends Canvas implements MouseListener, MouseMotionListener {
    ...
    public LineDrawer2() {
        ...
        addMouseListener(this);
        addMouseMotionListener(this);
    }

我的建议:每次你向一个类添加一个方法mousePressed()@Override如 这样,如果方法实际上没有覆盖任何方法,编译器将生成编译错误:

@Override
public void mousePressed(MouseEvent e) {

}
于 2012-12-30T16:57:25.760 回答