【问题标题】:Error while adding mouseListener to BufferedImage将 mouseListener 添加到 BufferedImage 时出错
【发布时间】:2013-08-01 03:14:07
【问题描述】:

我想在单击其中一个 buffereImage 时发出声音。但它向我显示了这个错误: BufferedImage 类型的方法 addMouseListener(new MouseAdapter(){}) 是未定义的

代码如下:

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new PropertionalLayoutManager(400, 400));
        add(new Symbol(), new PropertionalConstraint(0f, 0));
        add(new Symbol(), new PropertionalConstraint(0.67f, 0));
        //add(new Symbol(), new PropertionalConstraint(0f, 0.4675f));
        //add(new Symbol(), new PropertionalConstraint(0.67f, 0.4675f));
        add(new Drum(), new PropertionalConstraint(0.205f, 0.1f));
        add(new Drum(), new PropertionalConstraint(0.5f, 0.1f));
        add(new Drum(), new PropertionalConstraint(0f, 0.33f));
        add(new Drum(), new PropertionalConstraint(0.705f, 0.33f));


     DRUM.addMouseListener(new MouseAdapter()
     {
          public void mouseClicked(MouseEvent me) 
          {
            Sound1.Sound5.play();
          }
        }); 


    }static {

    try {
        SYMBOL = ImageIO.read(new File("HiCrash.png"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    try {
        DRUM = ImageIO.read(new File("HiTom.png"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}
}

【问题讨论】:

  • MouseListener 只能添加到可以在屏幕上显示的组件中。默认情况下,BufferedImage 不能在屏幕上显示,除非先被某些组件包裹(例如 JLabel 或绘制到 JPanel 的表面上)。
  • 那么如何将 bufferedImage 插入 JPanel?
  • 看看我的回答 ;)
  • 我要问:什么是属性?
  • @roippi 这是我前段时间为 jat 编写的自定义布局管理器,它尝试根据初始大小和 PropertionalConstraint(和首选大小)调整组件的大小。如果您真的很好奇,请查看stackoverflow.com/questions/17847816/…

标签: java eclipse swing bufferedimage mouse-listeners


【解决方案1】:

MouseListener 只能添加到可以在屏幕上显示的组件中。默认情况下,BufferedImage 不能在屏幕上显示,除非先被某些组件包裹(例如 JLabel 或绘制到 JPanel 的表面上)。

实际上,您不能将鼠标侦听器添加到任何不支持它的东西...

改为将MouseListener 添加到DrumSymbol

您可能需要阅读How to write a mouse listener

【讨论】:

  • 感谢@MadProgrammer。我还是不太明白。你帮了我很多忙
  • 我学得越多,我似乎知道的越少:P。最好的老师就是经验,继续努力,看看它会把你带到哪里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-04
  • 2013-06-29
  • 2018-02-19
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多