将mouseListener添加到BuffereImage时发生java错误
我想在点击我的一个buffereImage时发出声音。但它向我显示了一个错误:类型BuffereImage的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();
}
}
}
# 1 楼答案
MouseListener
只能添加到可以在屏幕上显示的组件中。默认情况下,BufferedImage
不能在屏幕上显示,除非先被某些组件包装(例如JLabel
或绘制在JPanel
的表面)实际上,你不能在任何不支持鼠标侦听器的地方添加鼠标侦听器
相反,将
MouseListener
添加到Drum
或Symbol
类中你可能想通读一下How to write a mouse listener