向图像添加动作侦听器

时间:2011-04-30 05:53:44

标签: java swing

我将图片插入JPanel。我写这段代码。

public void paint(Graphics g)
{

    img1=getToolkit().getImage("/Users/Boaz/Desktop/Piece.png");
    g.drawImage(img1, 200, 200,null);

}

我想为该图片添加一个动作侦听器,但它没有addActionListener()方法。如果不将图像放在按钮或标签中,我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

有几个选择。

直接在MouseListener

中使用JPanel

一种简单但又脏的方法是将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的任何部分即可视为对图片的点击。同样,在MouseListener中创建JComponent以捕获点击。

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());
  }
}

答案 1 :(得分:2)

最简单的方法是将图像放入JLabel。当您使用该程序时,它似乎只是图像,您无法在JLabel中告诉它。然后只需将一个MouseListener添加到JLabel。