将MouseListener添加到面板 [英] Adding a MouseListener to a panel
问题描述
我正在尝试将鼠标操作添加到我的面板中。
这是程序应该做的:
I am trying to add the mouse actions to my panel. This is what the program is supposed to do:
编写一个程序,允许用户用三个鼠标指定一个三角形印刷机。第一次鼠标按下后,画一个小点。在第二次鼠标按下后,绘制一条连接前两点的线。第三次鼠标按下后,绘制整个三角形。第四次鼠标按下删除旧三角形并开始一个新三角形。
Write a program that allows the user to specify a triangle with three mouse presses. After the first mouse press, draw a small dot. After the second mouse press, draw a line joining the first two points. After the third mouse press, draw the entire triangle. The fourth mouse press erases the old triangle and starts a new one.
推荐答案
我强烈要求建议您首先阅读如何编写鼠标监听器一>。当你遇到困难时,这些教程(以及JavaDocs)是开始的最佳场所
I would strongly recommend you start by having a read through How to Write a Mouse Listener. When ever you get stuck, these tutorials (and the JavaDocs) are the best place to get started
你问题的直接答案是,你需要注册一个您的组件的 MouseListener
的实例,可能类似于......
The "immediate" answer to your question is, you need to register an instance of the MouseListener
with your component, maybe something like...
private JPanel createCenterPanel() {
panel.addMouseListener(new MouseListen());
//panel.setLayout(null);
return panel;
}
这将回答你的直接问题。
This will "answer" your immediate issue.
但是,您会发现很难尝试将 MouseListener
的操作与面板结合起来,该面板需要绘制结果。
However, you'll find it hard to try and marry up the actions of the MouseListener
with the panel, which needs to paint the results.
一个更好的解决方案可能是从一个 JPanel
开始,它管理它自己的 MouseListener
A better solution might be to start with a JPanel
which manages it's own MouseListener
另外,图形g = panel.getGraphics()
不是如何自定义绘画应该执行。请查看执行自定义绘画以获取更多详细信息
Also, Graphics g = panel.getGraphics()
isn't how custom painting should be performed. Take a look at Performing custom painting for more details
所以相反,它看起来更像......
So, instead, it might look something more like...
public class TrianglePanel extends JPanel {
private List<Point> points = new ArrayList<>(3);
public TrianglePanel() {
addMouseListener(new MouseListen());
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
if (points.size() < 1) {
return;
}
for (int index = 0; index < points.size(); index++) {
Point nextPoint = points.get(index);
g.fillOval(nextPoint.x - 2, nextPoint.y - 2, 4, 4);
}
Point startPoint = points.get(0);
Point lastPoint = startPoint;
for (int index = 1; index < points.size(); index++) {
Point nextPoint = points.get(index);
g.drawLine(lastPoint.x, lastPoint.y, nextPoint.x, nextPoint.y);
lastPoint = nextPoint;
}
g.drawLine(lastPoint.x, lastPoint.y, startPoint.x, startPoint.y);
}
class MouseListen extends MouseAdapter {
public void mouseReleased(MouseEvent e) {
if (points.size() < 3) {
points.add(e.getPoint());
repaint();
}
}
}
}
这篇关于将MouseListener添加到面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!