我想制作一个带有图标拼贴的Swing程序,当你点击它们时会播放某些声音。为此,我创建了这个类:
public class Item extends JLabel implements MouseListener {
public Item(String s) {
// constructor setting background icon and private field with the sound to play
}
public void playSound(); //plays the sound
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Clicked");
this.playSound();
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
然后我创建了一个自定义JFrame
类:
public class Frame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 9221468315661092752L;
public static final int DEFAULT_FRAME_WIDTH=400;
public static final int DEFAULT_FRAME_HEIGHT=400;
private GridLayout gridLayout;
private ArrayList<Item> tiles=new ArrayList<Item>();
public Frame() {
super("Title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(DEFAULT_FRAME_WIDTH,DEFAULT_FRAME_HEIGHT));
gridLayout=new GridLayout(4,4,10,10);
setLayout(gridLayout);
addItems();
}
public void addItems() {
Item item=new Item("name");
Item item2=new Item("name");
tiles.add(item);
tiles.add(item2);
this.add(item);
this.add(item2);
}
public static void main(String[] args) {
Frame frame=new Frame();
frame.setVisible(true);
}
图块通常在网格布局中显示,但问题是鼠标监听器不起作用。我在println()
和mouseClicked()
放置的mousePressed()
未被调用。
我可以尝试向MouseListener
类添加Item
,以便Item
有一个MouseListener
,但我想知道上面的代码有什么问题。< / p>
答案 0 :(得分:0)
你有两个问题。一,你的JLabel没有显示(虽然我不确定是否故意遗漏)。二,你永远不会添加鼠标监听器。您可以通过向构造函数添加两个语句来完成此操作,而无需创建任何额外的类:
public Item(String s) {
super(s); //initializes the text and display using JLabel's constructor
addMouseListener(this); //uses the reference of this Item as a MouseListener
}