我的问题在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:我从上一个回复中了解到这是一个旧格式,但是,如果可能的话,请告诉我使用旧格式,我一定会学习新的。我真诚地感谢它。