创建动态按钮数组

Creating dynamic button arrays

我有一个循环来创建这样的按钮。这些按钮充当房间中的床(房间是一个 InternalFrame)。 addButtons 是一个 JButton 数组。

for (int i = 0; i < addButtons.length; i++) {
       addButtons[i] = new JButton("     Add Bed     "); // make text big
       addButtons[i].addActionListener(new AddBedListener());
       addButtons[i].setActionCommand("" + i);
       gbc.fill = GridBagConstraints.BOTH;
       room1Panel.add(addButtons1[i]);
    }   

我想添加一个允许我创建更多房间的功能,所以我创建了一个功能

public void createRoom(int nBeds, String bName){
    RoomFrame roomFrame = new RoomFrame();
    JPanel panel = new JPanel();

    for (int i = 0; i < nBeds; i++) {
           addButtons[i] = new JButton("     Add Bed     "); // make text big
           addButtons[i].addActionListener(new AddBedListener());
           addButtons[i].setActionCommand("" + i);
            gbc.fill = GridBagConstraints.BOTH;
           room4Panel.add(addButtons4[i]);
        }   
    BackButton backButton = new BackButton("Back");
}

问题是,我不知道如何动态创建一个按钮数组以供在我的代码中使用。代码需要知道一个房间中的按钮阵列与另一个房间中的按钮阵列不同,因此名称必须是唯一的。我如何拥有动态创建房间但允许我将每个按钮作为唯一实体引用的功能?

将唯一 ID 传递到您的 AddBedListener 构造函数中,该构造函数可用于唯一标识按钮,或者只是将唯一行为强制到 AddBedListener 的每个实例中。

The code needs to know that an array of buttons in one room is different to an array of buttons in another room, hence the name must be unique.

名称并不像许多编码新手认为的那么重要,变量名当然更是如此。更重要的是 references 以及如何访问引用。

最好的解决方案是使用 MVC 或模型-视图-控制程序结构来帮助组织代码。但如果这太复杂,那么房间的视图表示,这里的 RoomFrame 将保存这个列表,并且会有一个 addBed(Bed bed) 方法。最重要的是,Room 或 RoomFrame class 应该包含它自己的 Bed 对象的 ArrayList,例如:

List<Bed> bedList = new ArrayList<>(),

因此 Room 本身会跟踪自己的床,并准备好引用它拥有的所有床实例。底线:让您的对象 智能 以便它们知道自己的状态并可以根据该状态改变它们的行为。