Res*_*had 1 java swing dynamic jbutton
你好,我有这个设置
private JButton btnFoo, btnBar;
Run Code Online (Sandbox Code Playgroud)
我需要为每个按钮获取以下内容
btnFoo = new JButton("Foo");
btnFoo.addActionListener(this);
add(btnFoo);
Run Code Online (Sandbox Code Playgroud)
在Java中是否可以为我声明的每个按钮动态创建它?因为当我有5个按钮时,我不想要3x5 = 15行代码,而只需要几行动态创建按钮.
写一个小循环并将您的按钮存储在一个数组中:
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;
}
Run Code Online (Sandbox Code Playgroud)