gpt4 book ai didi

java - 多个 JButton 执行相同的任务

转载 作者:行者123 更新时间:2023-11-29 06:36:41 26 4
gpt4 key购买 nike

如何编写多个 JButton 对象来执行相同的任务?

我正在编写一个在游戏板上使用 25 个按钮的游戏。每个按钮通过生成随机数并根据数字更改图标来完成完全相同的事情。

这是我的代码:

    Random RG1 = new Random();
level_1_random_block = (RG1.nextInt(6));

final JButton btnNewButton = new JButton("");
btnNewButton.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent arg0) {
frame2.setVisible(false);
if (level_1_random_block == 0){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreDiamond.png"));
score += 100;
initialize_score();
}
if (level_1_random_block == 1){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreGold.png"));
score += 25;
initialize_score();
}
if (level_1_random_block == 2){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreGold.png"));
score += 25;
initialize_score();
}
if (level_1_random_block == 3){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreIron.png"));
score += 5;
initialize_score();
}
if (level_1_random_block == 4){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreIron.png"));
score += 5;
initialize_score();
}
if (level_1_random_block == 5){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\creeper.png"));
score -= 30;
initialize_score();
}
if (level_1_random_block == 6){
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\creeper.png"));
score -= 30;
initialize_score();
}

btnNewButton.removeMouseListener(this);
level_1_move_on = true;
continue_game();

}
});
btnNewButton.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\grass_side.png"));
btnNewButton.setBounds(0, 0, 87, 87);
frame1.getContentPane().add(btnNewButton);

一切正常,但我想知道是否有更简单的方法来对所有按钮进行编程,而无需编写 150 个不同的 if 语句。

最佳答案

我们通过覆盖actionPerformed 方法来创建一个ActionListener 子类,然后创建它的一个实例,将相同的实例添加到每个jButton 用例的对象。

class MyActionListener implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
// your action to be performed
}
}

注意 MouseListener 是 Swing 中的低级 AWT 事件监听器,其中 ActionListener 是更高的标签,更适合使用。但是,使用 java.swing.Action 会更好它本身就是一个action listener,它不仅提供了action-event处理,还提供了对action-event-firing组件状态的集中处理,比如tool bar按钮菜单项常用按钮文本字段

检查 How to Use Actions教程了解更多详情。

关于java - 多个 JButton 执行相同的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com