【发布时间】:2017-01-16 19:17:14
【问题描述】:
我基本上想制作一个用户可以在其中绘制分段线的单一窗口应用程序。申请流程应该是:
- 用户单击应用程序的唯一按钮以启动进程
- 用户通过单击段的第一个点进行选择
- 用户通过单击段的第二个点进行选择
我已经有了以下代码:
public class LineEditor extends JComponent{
private class Point{
int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
private class Line{
Point a, b;
public Line(Point a, Point b){
this.a = a;
this.b = b;
}
}
private ArrayList<Line> lines = new ArrayList<Line>();
public void setLine(Point a, Point b){
lines.add(new Line(a, b));
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.setColor(line.color);
g.drawLine(line.a.x, line.a.y, line.b.x, line.b.y);
}
}
public static void main(String[] args){
int height = 500, width = 500;
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Properties of the main window
frame.setAlwaysOnTop(true);
final LineEditor lineEditor = new LineEditor();
lineEditor.setPreferredSize(new Dimension(width, height));
JPanel panelCanvas = new JPanel();
panelCanvas.setPreferredSize(new Dimension(width, height));
JPanel secondaryPanel = new JPanel();
JButton addLineButton = new JButton("Add new line");
secondaryPanel.add(addLineButton);
frame.getContentPane().add(lineEditor, BorderLayout.CENTER);
frame.getContentPane().add(panelCanvas, BorderLayout.CENTER);
frame.getContentPane().add(secondaryPanel, BorderLayout.NORTH);
panelCanvas.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
}
});
addLineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// x
}
});
frame.pack();
frame.setVisible(true);
}
}
我不知道怎么做:
- 仅在用户按下按钮后激活 panelCanvas.addMouseListener。
- 从 addLineButton.addActionListener 获取鼠标坐标(点击后),这样我就可以创建两个 Point 对象,然后调用 lineEditor.setLine(pointA, pointB)
我想实现以下目标:
addLineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Wait for the first user click
int x1 = mouseListener.getX();
int y1 = mouseListener.getY();
Point a = new Point(x1, y1);
// Wait for the second user click
int x2 = mouseListener.getX();
int y2 = mouseListener.getY();
Point b = new Point(x2, y2);
lineEditor.setLine(a, b);
}
});
【问题讨论】:
-
您可能需要某种模型,
panelCanvas的MouseListener可以更新,addLineButton的ActionListener可以从中读取。就个人而言,我认为你可能会倒退,应该发生的是使用应该选择“画线”,然后在画布上单击他们想要绘制的点。同样,其中大部分将由某种模型控制 -
引用了一个例子here。
-
@trashgod 该示例与我正在寻找的内容无关,但仍然是一个有趣的示例。
-
@MadProgrammer,我终于以非常简单的方式解决了这个问题;只需通过各种方法实现鼠标侦听器即可。我已经发布了答案,以防有人发现它有用。