简体   繁体   中英

A method for automatically generating JButtons?

I am currently a java newbie of sorts writing a program that is, essentially, a board game, almost identical to checkers. Unfortunately, this also means I need one hundred JButtons for the checkerboard. I know there is a way to have automatically generated JButtons, I've seen it done. I have no idea how I would go about this, though. Any help would be appreciated!

If you want to generate a board game, you should use a GridLayout which will help you a lot positioning your buttons with minimal effort. Something like this:

public JPanel createBoardGame()
    JPanel boardGame = new JPanel(new GridLayout(numberOfRows,numberOfColumns));
    for (int i=0; i<numberOfRows*numberOfColumns; i++) {
        boardGame.add(new JButton(""));
    }
}

Here is a nice article that should help you a lot implementing your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM