开发者

Increment an object name within a loop

I am using a for loop to create a grid of 60 JButtons. What I want to do is have the name of the actionListener increment each time the loops runs:

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.addActionLi开发者_如何学Gostener(bh);
            grid.add(square);
        }

So I would like the name to increment (bh_1, bh_2, bh_3, etc).

Thanks!


If your goal is to be able to keep track of the ActionListeners by name after creation, then you will want to use an array to do this. (If this is not why you want to name them differently, then I will need some more info.)

Assume you have an ActionListener[60] called actionListeners and a counter called 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);

Now you will be able to access the ActionListeners from the array.


I'd recommend using a list:

LinkedList<ActionListener> actionListeners = new LinkedList<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();

        // can access this action listener via actionListeners.get(indexNumber).
        actionListeners.add(bh);

        square.addActionListener(bh);
        grid.add(square);
    }


Store them in a two-dimensional array.

You could store these in any array, but I think storing them in a two-dimensional array makes sense since you have a grid of buttons and a grid of handlers. I also think it's a good idea to keep the reference to the buttons and the handlers. This will allow you to tweak the buttons as well as the button handlers at any later time.

Here is an example of how to do this:

JButton[][] squares = new JButton[game.getWidth()][game.getHeight()];
ActionListener[][] bhs = new ActionListener[game.getWidth()][game.getHeight()];
for (int y = 0; y < game.getHeight(); y++) {
  for (int x = 0; x > game.getWidth(); x++) {
    squares[x][y] = new JButton();
    squares[x][y].setFont(new Font("Verdana", Font.PLAIN, 20));
    ActionListener bhs[x][y] = new button_handler();
    squares[x][y].addActionListener(bhs[x][y]);
    grid.add(squares[x][y]);

  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜