[英]How do I remove the border from multiple JButtons attached to one ActionListener (Created with for loop)?
[英]How do I put an ActionListener on a JButton created with an ArrayList of Jbuttons
我试图弄清楚如何在我从JButtons的arrayList创建的JButton上有一个动作列表器。
这是按钮的数组列表:
public static ArrayList<JButton> myTests;
public static ArrayList<JButton> selectedTests;
这是设置它们的逻辑:
public Devices(String[] testList, String title2)
{
myTests = createTestList(testList);
selectedTests = new ArrayList<JButton>();
checkedSerialNo = new ArrayList();
int numCols = 2;
//Create a GridLayout manager with
//four rows and one column
setLayout(new GridLayout(((myTests.size() / numCols) + 1), numCols));
//Add a border around the panel
setBorder(BorderFactory.createTitledBorder(title2));
for(JButton jcb2 : myTests)
{
this.add(jcb2);
}
}
private ArrayList<JButton> createTestList(String[] testList)
{
String[] tests = testList;
ArrayList<JButton> myTestList = new ArrayList<JButton>();
for(String t : tests)
{
myTestList.add(new JButton(t));
}
for(JButton jcb2 : myTestList)
{
jcb2.addItemListener(this);
}
return myTestList;
}
@Override
public void itemStateChanged(ItemEvent ie)
{
if(((JButton)ie.getSource()).isSelected())
{
selectedTests.add((JButton) ie.getSource());
}
}
public ArrayList<JButton> getSelectedTests()
{
return selectedTests;
}
我不知道如何为数组列表中的生成按钮制作actionListner或onClickListener。
任何见解和帮助表示赞赏。
谢谢!
Ironmantis7x
最简单的方法就是创建内部私有类。
private class MyTestListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// stuff that should happen
}
}
private class SelectedTestListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// stuff that should happen
}
}
私有类需要在同一个Java文件中(与ArrayLists一起使用)。 创建类后,只需添加操作侦听器。
MyTestListener handler = new MyTestListener();
//Inside the for-each
button.addActionListener(myListener);
如果您只需要1个侦听器(对于一种按钮类型,例如itemStateListener),则只需定义一个具有合适名称的私有类,然后使用上述功能将其添加到foreach的按钮中即可。
祝你今天愉快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.