1

I am making a desktop application in java where I want to create the buttons dynamically. The dynamically created button should be placed in a grid like structure. Now my concern is that, if I want to access those buttons, then how can i do that since I dont have the ID of the particular button ?

setLayout(new java.awt.GridLayout(4, 4));
        for (int i = 0; i < dataCount; i++)
        {
            GridBagConstraints c = new GridBagConstraints();
            jPanel1.setLayout(new GridBagLayout());

            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 0;
            c.gridx = 0;
            c.gridy = 0;
            jPanel1.add(new JButton(linesArray[i]), c);        

            jPanel1.setBackground(Color.WHITE);
            jPanel1.setBorder(BorderFactory.createMatteBorder(0,0,1,0,Color.BLACK));

        }

How can i access the butons through a particular ID?

1 Answer 1

1

You can create an array which will hold all your buttons:

JButton[] buttons = new JButton[dataCount];

and then add buttons to it, and call the button by array:

buttons[i] = new JButton(linesArray[i]), c);
jPanel1.add(buttons[i]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.