2011-04-30 98 views
0

我将图像插入JPanel。我写这个代码。将动作侦听器添加到图像

public void paint(Graphics g) 
{ 

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

} 

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

+3

1)对于绘制图像,只需要一个“JComponent”。 2)对于'JComponent'或'JPanel',重写'paintComponent(Graphics)'而不是'paint(Graphics)'3)不要尝试在paint方法中加载图像。将它加载到'init()'或构造过程中并将其作为类级属性存储。 4)'Toolkit'图像加载方法需要一个'MediaTracker'。使用'ImageIO.read(文件)'来保证图像被加载。 5)在'drawImage()'方法中为'this'交换'null'。 – 2011-04-30 06:13:16

回答

4

有几个选项。

使用在JPanel

一个MouseListener直接一个简单而肮脏的方式将是直接添加MouseListener到您推翻了paintComponent方法JPanel,并实现了一个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()); 
    } 
} 
+2

按照@ user650679的历史记录看来,您的答案在近期内不会被承认/接受:)。虽然我的投票是+1。 – Favonius 2011-04-30 06:11:05

+0

@Favonius:希望这个答案也能在将来帮助其他人。谢谢你的赞成:) – coobird 2011-04-30 06:15:33

+1

你的代码不遵循你的描述(幸运的是:-) a)它正确地覆盖了_paintComponent_(与第一个例子中描述的paint相比)b)它正确地使用了MouseListener(相对于已实现的规定) – kleopatra 2011-04-30 09:30:41

2

最简单的方法是将图像放入JLabel中。当你使用该程序时,它看起来只是图像,你不能在JLabel中告诉它。然后,只需将一个MouseListener添加到JLabel。

+2

这个问题具体问到如何做到这一点,而不会将其放入标签中,因此您的回复最好作为评论,而不是回答。 – 2012-11-08 15:25:29

相关问题