首页 文章

Java:创建多个(重复)按钮,这些按钮对自己执行相同的操作

提问于
浏览
1

背景信息:我想制作一个9x9网格的按钮作为空床 . 所有按钮都说“添加床”,点击后打开一个窗口来写入有关乘员的数据 . 保存后,按钮将变为占用的床位图像 .

问题:是否可以创建一个事件监听器,为每个按钮执行相同的操作,但是将其应用于按下的按钮?我是java新手,但我知道好的代码应该可以在几行而不是100行中完成

码:

//button1 (inside the gui function)
    addBed1 = new JButton("Add bed"); //button 1 of 9
    addBed1.addActionListener(new room1Listener());

class room1Listener implements ActionListener{
    public void actionPerformed(ActionEvent event){
        addBed1.setText("Adding bed..);
        addBedGui(); //Generic window for adding bed info.
    }
}

1 回答

  • 4

    是否可以创建一个事件监听器,为每个按钮执行相同的操作,但是将其应用于按下的按钮?我是java新手,但我知道好的代码应该可以在几行而不是100行中完成

    绝对 . 实际上,您可以创建一个ActionListener对象,并将此相同的侦听器添加到for循环中的每个按钮 . ActionListener将能够通过 ActionEvent#getSource() 方法获取对按下它的按钮的引用,或者您可以通过 ActionEvent#getActionCommand() 方法获取JButton的actionCommand String(通常是其文本) .

    例如 . ,

    // RoomListener, not roomListener
    class RoomListener implements ActionListener{
        public void actionPerformed(ActionEvent event){
            AbstractButton btn = (AbstractButton) event.getSource();
            btn.setText("Adding bed..);
            addBedGui(); //Generic window for adding bed info.
        }
    }
    

    RoomListener roomListener = new RoomListener();
    JButton[] addButtons = new JButton[ADD_BUTTON_COUNT];
    for (int i = 0; i < addButtons.length; i++) {
       addButtons[i] = new JButton("     Add Bed     "); // make text big
       addButtons[i].addActionListener(roomListener);
       addBedPanel.add(addButtons[i]);
    }
    

相关问题