这里的问题有三个方面:
实现上述要点的一种方法是子类化JPanel并提供这些功能.
1.在面板中显示背景图像.
首先,由于JPanel默认情况下无法显示背景图像,因此必须有一种方法可以将图像保存在图像中JPanel,然后在面板上绘制图像,这可以通过该paintComponent方法执行.
实现此目的的一种方法是在类中有一个字段,Image用于绘制:
class MyPanel extends JPanel {
// Background image. Initialize appropriately.
Image backgroundImage;
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw background image each time the panel is repainted.
g.drawImage(backgroundImage, 0, 0, null);
}
}
Run Code Online (Sandbox Code Playgroud)
所述Graphics在对象paintComponent与相关联的MyPanel,并且可以被用于执行图形操作.
2.找到单击鼠标的点.
其次,为了取回被点击鼠标,在这一点,我们可以指定一个MouseListener到MyPanel.在以下示例中,扩展的匿名内部类MouseAdapter用于最小化编写额外代码:
class MyPanel extends JPanel {
// Background image. Initialize appropriately.
Image backgroundImage;
public MyPanel() {
// Add a MouseListener which processes mouse clicks.
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Process mouse-click.
}
})
}
// paintComponents method here.
}
Run Code Online (Sandbox Code Playgroud)
单击鼠标时需要执行的处理可以包含在mouseClicked方法中.
3.如何在面板上画一个点.
第三,为了找到点击鼠标的一个点,可以MouseEvent从mouseClicked方法传入的对象中获取它:
class MyPanel extends JPanel {
// Background image. Initialize appropriately.
Image backgroundImage;
Point pointClicked;
public MyPanel() {
// Add a MouseListener which processes mouse clicks.
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Retrieve the point at which the mouse was clicked.
pointClicked = e.getPoint();
// Repaint the panel.
this.repaint();
}
})
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw background image each time the panel is repainted.
g.drawImage(backgroundImage, 0, 0, null);
// Draw a little square at where the mouse was clicked.
g.fillRect(pointClicked.x, pointClicked.y, 1, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然上面的代码没有经过测试,但它应该是一个起点.
例如,如果需要绘制多个点,可能List<Point>需要保持点,并且可以Point在paintComponents方法中绘制每个点.
如果在单击鼠标时需要执行其他处理,则可以向该mouseClicked方法添加其他代码.
其他资源:
感谢zedoo在评论中指出super.paintComponent应该在覆盖paintComponent方法时执行调用.