C:\Users\DylanW\Desktop\Games\Dylancraft\Dylancraft-Alpha 1.0>2to3 -w MineCraft.py
我正在尝试使用用户鼠标输入来绘制三角形。我也有一个trianglecomponent类以及在这里使用xs和ys的构造函数。所以我最后使用了println,看到代码在xs和ys之前运行。如何在绘制任何内容之前更改此设置以从鼠标获取xs和ys
答案 0 :(得分:0)
您需要在事件处理中创建绘图部分,以便将侦听器之后的所有内容移动到侦听器中,以便在阅读第三次单击后立即绘制三角形。
答案 1 :(得分:0)
在您的代码中,您在创建TriangleComponent
之前知道在哪里绘制它(x1,x2,y1,ecc ...)。
要解决此问题,只需在拥有所有坐标后(第三次点击后)创建TriangleComponent
:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Viewer implements MouseListener
{
static int counter = 0;
static double x1, x2, x3, y1, y2, y3;
public static void main (String [] args)
{
final JFrame outerFrame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(400,400);
outerFrame.setSize(400, 400);
outerFrame.setTitle("Drawing Triangle");
outerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outerFrame.add(panel);
panel.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e){
if(counter == 0) {
x1 = e.getX();
y1 = e.getY();
} else if(counter == 1) {
x2 = e.getX();
y2 = e.getY();
} else if(counter == 2) {
x3 = e.getX();
y3 = e.getY();
TriangleComponent component = new TriangleComponent(x1, x2, x3, y1, y2, y3);
outerFrame.add(component);
System.out.println(x2);
System.out.println(y2);
System.out.println(x1);
System.out.println(y1);
System.out.println(x3);
System.out.println(y3);
}
counter++;
}
});
panel.setFocusable(true);
outerFrame.setVisible(true);
}
}