我的问题已经在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) {
}
}
附注:我从上一个答复中了解到,这是一种旧格式,但是,如果可能的话,请告诉我使用旧格式,我也一定会学习新格式。我衷心感谢。
最佳答案
您正在初始化局部变量,而不是初始化事件处理方法中的字段。代替
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) {
}