【发布时间】:2012-12-15 01:53:38
【问题描述】:
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) {
}
}
P.S.:我从上次回复中了解到这是一种旧格式,但是,如果可能的话,请告诉我使用旧格式,我一定会学习新格式。我真诚地感谢它。
【问题讨论】:
标签: java graphics drawing awt mouseevent