向图像添加动作侦听器

use*_*679 0 java swing

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

public void paint(Graphics g)
{

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

}
Run Code Online (Sandbox Code Playgroud)

我想向该图片添加一个动作监听器,但是它没有addActionListener()方法。如何在不将图像放入按钮或标签的情况下做到这一点?

coo*_*ird 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:ActionListener无法将添加到中JPanel,因为JPanel本身不适合创建“动作”。

创建一个JComponent以显示图像,然后添加一个MouseListener

更好的方法是创建一个新的子类,JComponent其唯一目的是显示图像。本JComponent应大小本身对图片的大小,使一点击的任何部分JComponent可以考虑在图像上点击。再次,建立MouseListenerJComponent以捕获点击。

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());
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 根据@ user650679的历史记录,您的答案似乎在不久的将来不会被确认/接受:)。虽然我的投票是+1。 (2认同)