Natacha
Natacha

Reputation: 1957

JButton table java

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 ?

Upvotes: 1

Views: 516

Answers (2)

Reimeus
Reimeus

Reputation: 159754

The simplest way would be to use a GridLayout and add all your buttons to that container.

Grid Table Demo

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();
            }
        });
    }
}

Upvotes: 1

Eich
Eich

Reputation: 3788

You can use MiG Layout to easily place all of your items in your JFrame (not only to place your buttons). It makes the placement of your items much easier with less code.

Upvotes: 2

Related Questions