本文介绍了动态创建JButtons的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我有这个设置
private JButton btnFoo, btnBar;
我需要获得以下每个按钮
And I need to get for each button the following
btnFoo = new JButton("Foo");
btnFoo.addActionListener(this);
add(btnFoo);
在Java中是否可以为我声明的每个按钮动态创建它?
,因为当我有5个按钮时,我不想要3x5 = 15行代码,只需要几行动态创建按钮。
Is it possible in Java to create this dynamically for each button I declare?because when I have like 5 buttons I don't want 3x5 = 15 lines of code but only a few lines with dynamically created buttons.
推荐答案
写一个小循环并将你的按钮存储在一个数组中:
Write a little loop and store your buttons in an array:
private JButton buttons[] = new JButton[5];
String names[] = {"Foo", "Bar", "Baz", "Fob", "Bao"};
for (int i = 0; i < buttons.length; ++i)
{
JButton btn = new JButton(names[i]);
btn.addActionListener(this);
add(btn);
buttons[i] = btn;
}
这篇关于动态创建JButtons的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!