Reputation: 5157
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?
Upvotes: 1
Views: 448
Reputation: 5395
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]);
Upvotes: 1