我的java gui有问题:(我希望你会帮助我:)。
我有一个黑色的gui,当我在gui中用鼠标点击时,程序会将点击的坐标保存在Point之前。然后,当我点击第二个位置时,程序会在Point current中保存第二个点击坐标,并在“previous”和“current”之间画一条线。
但是现在我希望当我第三次在gui中点击时,程序将在第二次点击和第三次点击之间绘制一条线,依此类推。 第五个之间的第四个。
我该怎么做?
这是我的代码:
public class OdometerPanel extends JPanel {
private double totalDistance;
private Point previous = null, current = null;
private ArrayList<Point> travelledPoints;
private int p1x, p2x, p1y, p2y;
private double distance;
JLabel pointco = new JLabel("");
JLabel trav = new JLabel("Travelled Distance: " + distance);
public OdometerPanel() {
LineListener listener = new LineListener();
addMouseListener(listener);
addMouseMotionListener(listener);
trav.setForeground(Color.green);
pointco.setForeground(Color.yellow);
add(pointco);
add(trav);
setBackground(Color.black);
setPreferredSize(new Dimension(400, 200));
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor (Color.yellow);
if (previous != null && current != null)
page.drawLine(previous.x, previous.y, current.x, current.y);
}
private class LineListener implements MouseListener,
MouseMotionListener
{
public void mouseClicked(MouseEvent event)
{
if(previous == null && current == null) {
previous = event.getPoint();
p1x = (int) previous.getX();
p1y = (int) previous.getY();
pointco.setText("P(" + p1x + "," + p1y + ")");
}
else {
current = event.getPoint();
p2x = (int) current.getX();
p2y = (int) current.getY();
distance = (int) Math.sqrt((p2x - p1x)*(p2x - p1x) + (p2y - p1y) * (p2y - p1y));
trav.setText("Travelled Distance: " + distance);
pointco.setText("P(" + p2x + "," + p2y + ")");
repaint();
}
}
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseMoved(MouseEvent event) {}
public void mouseDragged(MouseEvent event) {}
}
}
提前谢谢你:D``
答案 0 :(得分:0)
您的mouseClicked
代码应该更多。
if(current == null) {
current = event.getPoint();
p1x = (int) current.getX(); p1y = (int) current.getY();
pointco.setText("P(" + p1x + "," + p1y + ")");
} else {
previous = current;
current = event.getPoint();
p1x = (int) previous.getX();
p1y = (int) previous.getY();
p2x = (int) current.getX();
p2y = (int) current.getY();
distance = (int) Math.sqrt((p2x - p1x)*(p2x - p1x) + (p2y - p1y) * (p2y - p1y));
trav.setText("Travelled Distance: " + distance);
pointco.setText("P(" + p2x + "," + p2y + ")");
repaint();
}
不确定previous = current
是否真的有效。你可能需要更像
previous = new Point(current.getX(), current.getY());
这取决于Point类可用的构造函数。
答案 1 :(得分:0)
我假设您想要同时绘制多条线,这意味着您需要保留所有点的列表。
在主要班级:
List<Point> points = new ArrayList<>();
@Override
public void paintComponent(Graphics page) {
super.paintComponent(page);
page.setColor(Color.yellow);
for(int i= 1; i < points.size(); i++) {
Point p1 = points.get(i-1);
Point p2 = points.get(i);
page.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
在MouseListener中
public void mouseClicked(MouseEvent event) {
points.add(event.getPoint());
}