我正在使用 for 循环创建一个包含 60 个 JButton 的网格。我想要做的是每次循环运行时增加 actionListener 的名称:
for (int y = 0; y < game.getHeight(); y++) {
for (int x = 0; x < game.getWidth(); x++) {
JButton square = new JButton();
square.setFont(new Font("Verdana", Font.PLAIN, 20));
ActionListener bh = new button_handler();
square.addActionListener(bh);
grid.add(square);
}
所以我希望名称递增(bh_1、bh_2、bh_3 等)。
谢谢!
最佳答案
如果您的目标是能够在创建后按名称跟踪 ActionListeners
,那么您将需要使用数组来执行此操作。 (如果这不是您想要以不同方式命名它们的原因,那么我将需要更多信息。)
假设您有一个名为 actionListeners
的 ActionListener[60]
和一个名为 buttonCount
的计数器。
JButton square = new JButton();
square.setFont(new Font("Verdana", Font.PLAIN, 20));
ActionListener bh = new button_handler();
actionListeners[buttonCount++] = bh; // store the handler in an array for later
square.addActionListener(bh);
grid.add(square);
现在您将能够从数组访问ActionListeners
。
关于java - 在循环内递增对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4795463/