gpt4 book ai didi

关于允许用户画线的 Java 挑战

转载 作者:行者123 更新时间:2023-12-01 14:58:01 29 4
gpt4 key购买 nike

我的问题已在 java draw line as the mouse is moved 中提到过然而,我对这本书的了解还不够深入,无法涵盖 JPanels、JFrames 和 Points,正如提出这个问题的前程序员所述。

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

根据我正在使用的文本(因为我正在自学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 dragging the 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 released, the line is drawn.

正如您所认识到的,运行该程序不会由用户创建任何绘图。我相信遇到此错误是由于第 21 行:g.drawLine(x, y, x2, y2); 不正确,因为这是定义线条绘制的语句。

非常感谢任何帮助。预先感谢您就此事所付出的所有时间和合作。

我回答问题的代码是:

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

public class LineDrawer extends Canvas
implements MouseListener, MouseMotionListener {
int x, y, x2, y2;

public LineDrawer() {
super();
setSize(300, 200);
setBackground(Color.white);
}
public void mouseClicked(MouseEvent me) {
int x = me.getX();
int y = me.getY();
int x2 = me.getX();
int y2 = me.getY();

}
public void paint(Graphics g) {
g.drawLine(x, y, x2, y2);
g.setColor(Color.blue);
}


public void mousePressed(MouseEvent me) {
repaint();
}

public void mouseDragged(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}


public void mouseReleased(MouseEvent me) {
}
public void mouseMoved(MouseEvent me) {
}

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

}

P.S.:我一直在犹豫是否要寻求帮助,因为我担心其他程序员会用我还没有学过的方法来回答。

最佳答案

int x1, y1, x2, y2;

public void mousePressed(MouseEvent e){
x1 = e.getX();
y1 = e.getY();
}

public void mouseDragged(MouseEvent e){
x2 = e.getX();
y2 = e.getY();
// Now Paint the line
repaint();
}

希望有帮助。

关于关于允许用户画线的 Java 挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088470/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com