1

I am working with Swing and I created a JFrame in which I put 9 buttons. But I need to access quickly to these buttons, so I would like to create a table of all my JButtons, where I'll be able to access rapidly the buttons. But I dont find the syntax to declare it...

Can you help me ?

4

2 回答 2

2

您可以使用MiG Layout轻松地将所有项目放置在 JFrame 中(不仅仅是放置按钮)。它使您的项目的放置更容易,代码更少。

于 2013-04-04T13:57:02.583 回答
1

最简单的方法是使用 aGridLayout并将所有按钮添加到该容器中。

网格表演示

public class GridDemo {

    public void showUI() {
        JFrame frame = new JFrame("Grid \"Table\" Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLayout(new GridLayout(0, 3));

        for (int i=0; i < 9; i++) {
            frame.add(new JButton("Button " + (i + 1)));
        }

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                GridDemo gridDemo = new GridDemo();
                gridDemo.showUI();
            }
        });
    }
}
于 2013-04-04T13:51:58.847 回答