如何在程序运行时添加按钮

时间:2013-10-28 15:17:21

标签: java swing awt

我需要在计算要添加的按钮数量时添加按钮。

我的按钮创建代码在这里..:

private void loadButtons()
{
    if (active_puzzle != null)
    {
        int devider = 5;
        int count = 0;
        JButton puzzleButton[] = new JButton[active_puzzle.getNumberOfPieces()];
        for(int row = 0; row < active_puzzle.getRows(); row++)
        {
            for(int column = 0; column < active_puzzle.getColumns(); column++)
            {
                puzzleButton[count] = new JButton(new ImageIcon( active_puzzle.getPieces()[count].getPieceImage() ) );
            }
        }
    }
}

现在我如何告诉程序需要将新按钮添加到屏幕上?

谢谢

2 个答案:

答案 0 :(得分:4)

将组件添加到可见GUI的基本代码是:

panel.add(...);
panel.revalidate();
panel.repaint();

然后布局管理员可以完成它的工作。

答案 1 :(得分:0)

将存储在puzzleButton数组中的所有新创建的按钮添加到程序的主要JPanel中。