gpt4 book ai didi

Java根据鼠标点击绘制三个形状?

转载 作者:行者123 更新时间:2023-12-01 13:19:33 24 4
gpt4 key购买 nike

我是 Java 绘图新手,在使用鼠标监听器事件时遇到了一些问题。我想做的是在单击时绘制一个点,然后在单击时绘制一条从该点延伸的线,最后单击时的最后一个点连接起来形成一个三角形。到目前为止,我只是致力于让点和线发挥作用。我认为我现在的方式已经很接近了;在顶角绘制一个圆圈,而不是用户单击的位置,但单击时会从圆圈所在的位置绘制一条线。尝试使用 boolean 值来决定何时应该绘制某些内容,但没有成功。感谢您的帮助。

主类

package TriangleDraw;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TriangleDrawMain {

public static void main(String[] args) {
//create a frame or window

JFrame frame = new JFrame();
//set window size
frame.setSize(500, 500);
//set the title
frame.setTitle("Triangle Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//add panel to frame and make it visible
MouseComponent component = new MouseComponent();
frame.add(component);
frame.setVisible(true);

}
}

绘画课

package TriangleDraw;
import java.util.*;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.geom.*;

public class MouseComponent extends JPanel implements MouseListener{
boolean drawPoint = true;
boolean drawLine = false;
boolean drawTriangle = false;

public MouseComponent(){
super();
pointX = 0;
pointY = 0;
oldX = 0;
oldY = 0;
addMouseListener(this);
}

int pointX, pointY, oldX,oldY;

@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
if(drawPoint == true){
g.drawOval(pointX,pointY,10,10);
drawPoint = false;
drawLine = true;
oldX = pointX;
oldY = pointY;
}
if(drawLine == true){
g.drawLine(pointX, pointY, oldX, oldY);
}


}

public void mouseClicked(MouseEvent mouse){

pointX = mouse.getX();
pointY = mouse.getY();

repaint();
}
public void mouseEntered(MouseEvent mouse){ }
public void mouseExited(MouseEvent mouse){ }
public void mousePressed(MouseEvent mouse){ }
public void mouseReleased(MouseEvent mouse){ }
}

最佳答案

我不会改变paintComponent中的状态,你不知道什么时候会调用它(你分配oldX和oldY的地方)。我建议创建两个 Point 对象,并在每个其他 mouseClicked 事件中在这两个点对象之间切换。

如果在 mouseClicked 之间多次调用 PaintComponent,则最终将 oldX 和 OldY 等于 pointX 和 pointY。

关于Java根据鼠标点击绘制三个形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155234/

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