我将图像插入到 JPanel
中。我写了这段代码。
public void paint(Graphics g)
{
img1=getToolkit().getImage("/Users/Boaz/Desktop/Piece.png");
g.drawImage(img1, 200, 200,null);
}
我想向该图片添加一个 Action 监听器,但它没有 addActionListener()
方法。如何在不将图像放入按钮或标签中的情况下做到这一点?
最佳答案
有几个选项。
直接在 JPanel
中使用 MouseListener
一个简单但肮脏的方法是添加 MouseListener
直接到JPanel
您在其中覆盖了 paintComponent
方法,并实现 mouseClicked
检查图像所在区域是否已被单击的方法。
一个例子是:
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
的任何部分都可以被视为单击图像。再次,在 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());
}
}
关于java - 向图像添加 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5839882/