Java 将操作侦听器添加到图像
我将图像插入Java 将操作侦听器添加到图像,java,swing,Java,Swing,我将图像插入JPanel。我写这段代码 public void paint(Graphics g) { img1=getToolkit().getImage("/Users/Boaz/Desktop/Piece.png"); g.drawImage(img1, 200, 200,null); } 我想向该图片添加一个操作侦听器,但它没有addActionListener()方法。如何在不将图像放入按钮或标签的情况下执行此操作?有几个选项 直接在JPanel中使用MouseL
JPanel
。我写这段代码
public void paint(Graphics g)
{
img1=getToolkit().getImage("/Users/Boaz/Desktop/Piece.png");
g.drawImage(img1, 200, 200,null);
}
我想向该图片添加一个操作侦听器,但它没有
addActionListener()
方法。如何在不将图像放入按钮或标签的情况下执行此操作?有几个选项
直接在JPanel中使用MouseListener
一个简单但肮脏的方法是,直接向中添加一个覆盖该方法的方法,并实现一个检查图像所在区域是否已被单击的方法
例如:
class ImageShowingPanel extends JPanel {
// The image to display
private Image img;
// The MouseListener that handles the click, etc.
private MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Do what should be done when the image is clicked.
// You'll need to implement some checks to see that the region where
// the click occurred is within the bounds of the `img`
}
}
// Instantiate the panel and perform initialization
ImageShowingPanel() {
addMouseListener(listener);
img = ... // Load the image.
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
注意:ActionListener
不能添加到JPanel
,因为JPanel
本身不能创建被认为是“动作”的内容
创建一个JComponent
以显示图像,并添加一个MouseListener
更好的方法是创建一个新的子类,其唯一目的是显示图像。JComponent
应该根据图像的大小调整自身的大小,这样点击JComponent
的任何部分都可以被视为点击图像。同样,在JComponent
中创建一个MouseListener
,以捕获点击
class ImageShowingComponent extends JComponent {
// The image to display
private Image img;
// The MouseListener that handles the click, etc.
private MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Do what should be done when the image is clicked.
}
}
// Instantiate the panel and perform initialization
ImageShowingComponent() {
addMouseListener(listener);
img = ... // Load the image.
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
// This method override will tell the LayoutManager how large this component
// should be. We'll want to make this component the same size as the `img`.
public Dimension getPreferredSize() {
return new Dimension(img.getWidth(), img.getHeight());
}
}
最简单的方法是将图像放入JLabel中。当您使用该程序时,它似乎只是图像,您无法在JLabel中分辨它。然后只需在JLabel中添加一个鼠标侦听器。根据@user650679历史记录,您的答案似乎在不久的将来不会被确认/接受:)。虽然我投了+1票。@Favonius:希望这个答案也能帮助其他人。感谢您的投票:)您的代码没有遵循您的描述(幸运的是:-)a)它正确地覆盖了paintComponent(与第一个示例中所述的paint相比)b)它正确地使用了MouseListener(与已实现的声明相比)@kleopatra感谢您指出描述和代码之间的不匹配。已经有一段时间了,但我已经做了一些更改来解决这个问题。:)我想在一个屏幕上添加多个图像,并使每个图像都可以点击。因此我必须制作许多JComponent?1)为了绘制图像,只需要一个
JComponent
。2) 对于JComponent
或JPanel
,覆盖paintComponent(Graphics)
,而不是paint(Graphics)
3)不要尝试在绘制方法中加载图像。将其加载到init()
或在构造期间,并将其存储为类级属性。4) Toolkit
图像加载方法需要一个MediaTracker
。使用ImageIO.read(文件)
可确保图像已加载。5) 在drawImage()
方法中,将null
替换为this
。该问题专门询问如何在不将其放入标签的情况下执行此操作,因此您的回答最好是作为注释,而不是答案。