gpt4 book ai didi

java - 在 mouseDragged 中设置终点并在 mousePressed 中使用它

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:23 24 4
gpt4 key购买 nike

我正在创建一个程序,您可以在其中在面板上绘制(线条、椭圆形或矩形)并指定颜色、宽度、填充等。我有一个实现 MouseMotionListener 和 MouseListener 的 JPanel 类。

这是 mouseDragged 方法的代码:

@Override
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}

这是 mousePressed 方法的代码:

    public void mousePressed(MouseEvent e) { 

Paint c = window.getFirst();
second = window.getSecond();

int shapeOption= window.getShapeSelect();
//System.out.println(shapeOption);
boolean fill = window.getFilled();

BasicStroke s = new BasicStroke(window.getLineWidth()); //may not need new BasicStroke()

pointStart = e.getPoint();

Shape temp;


switch (shapeOption) {
case 0:
temp = new Line(pointStart, pointEnd, s, c);
case 1:
temp = new Rectangles(pointStart, pointEnd, s, c, fill);
default:
temp = new Oval(pointStart, pointEnd,s,c, fill);
}

shapes.add(temp);

}

我对该程序有两个问题。 switch 语句未按预期工作。即使 shapeOption 正确更新,它也只使用默认情况。对于新线和新矩形,我收到警告“从未使用分配的值”。

我遇到的另一个问题是该程序只得出很少的点。我相信这是因为它在按下鼠标时创建了形状,此时 pointEnd 与 pointStart 相同。我怎样才能做到在 mouseDragged 方法完成之前才传递 pointEnd ?

我希望这是有道理的,任何帮助都会受到赞赏。

最佳答案

对于你的两个问题:

1) 在每个 case 语句的末尾需要 break;;否则,控制将通过所有 case 语句传递,并且 temp 将始终设置为 Oval

2) mousePressed()mouseDragged() 之前被调用。您应该在 mouseDragged() 中进行绘制以使其生效,或者在 mouseReleased() 中进行绘制以仅在形状完成时进行绘制。您可能还需要一个标志来检查鼠标是否在 mousePressed()mouseReleased() 之间移动了足够远的距离,以便您不会在非拖动的点击事件上绘制点。

关于java - 在 mouseDragged 中设置终点并在 mousePressed 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427821/

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