所以我试图在一个动作监听器中为我的一个按钮调用一个方法,但是一个错误不断出现,说明未处理的异常类型
public static void randomRoll(final JPanel panel, final int array[]) throws Exception
{
final ImageIcon icon = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Dice-1.png/45px-Dice-1.png"));
final ImageIcon icon1 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Dice-2.png/45px-Dice-2.png"));
final ImageIcon icon2 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Dice-3.png/45px-Dice-3.png"));
final ImageIcon icon3 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Dice-4.png/45px-Dice-4.png"));
final ImageIcon icon4 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Dice-5.png/45px-Dice-5.png"));
final ImageIcon icon5 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Dice-6.png/45px-Dice-6.png"));
//final ImageIcon [] diceIcons = {icon, icon1, icon2, icon3, icon4, icon5};
final JButton dice = new JButton ("Roll Dice");
dice.setBounds(40, 40, 100, 30);
panel.add(dice);
panel.setLayout(null);
dice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
randomDice(array, panel, icon, icon1, icon2, icon3, icon4, icon5);
}
});
答案 0 :(得分:0)
dice.addActionListener(this);
@Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == dice) {
randomDice(array, panel, icon, icon1, icon2, icon3, icon4, icon5);
}
}
答案 1 :(得分:0)
您可以使用:
JButton addButton = new JButton("Add");
addButton.addActionListener(this);
addButton.setActionCommand("add");
然后:
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("add")){
System.out.println("from add button");
}
}
答案 2 :(得分:0)
好的,你必须看这个...... 不要在 randomRoll 中设置 actionListener (它看不到它) 将actionListener转换为另一种方法或任何你想要的方法(只是没有 进入这种方法)。 祝你好运..