我正在java中创建一个桌面应用程序,我想动态创建按钮。动态创建的按钮应放置在网格状结构中。现在我担心的是,如果我想访问这些按钮,那么我怎么能这样做,因为我没有特定按钮的ID?
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));
}
如何通过特定ID访问按钮?
答案 0 :(得分:1)
您可以创建一个array
来保存所有按钮:
JButton[] buttons = new JButton[dataCount];
然后添加按钮,然后按array
:
buttons[i] = new JButton(linesArray[i]), c);
jPanel1.add(buttons[i]);