I have an array I fill with buttons and I want an individual button to change its text when clicked.
我有一个数组,我填充了按钮,我想要一个单独的按钮,以便在单击时更改其文本。
for (int i = 0; i<4; i++)
{
button[i] = new JButton ("Add");
button[i].addActionListener(this);
box[i] = new JComboBox();
foodOptions.add(box[i]);
foodOptions.add(button[i]);
}
public void actionPerformed (ActionEvent e)
{
button[this].setText("I've been clicked!");
}
The current doesn't work because of incompatible types, what format is appropriate?
由于类型不兼容,当前不起作用,哪种格式合适?
1 个解决方案
#1
5
Yes, it makes no sense to pass an object, this
, into an array index which expects an int, not your GUI object, so I'm not sure what you were trying to achieve with this.
是的,将一个对象传递给一个需要int而不是GUI对象的数组索引是没有意义的,所以我不确定你试图通过它实现什么。
Just get a reference to the JButton that's been clicked from the ActionEvent's getSource()
method:
只需获取从ActionEvent的getSource()方法中单击的JButton的引用:
JButton btn = (JButton)e.getSource();
btn.setText("I've been clicked");
Edit:
Also you should avoid using this
as your ActionListener since this means that you're likely having your GUI class implement an ActionListener which is asking the poor class to be too many things, to do too much. You're much better off either using anonymous inner classes or else even better use AbstractActions.
编辑:你也应该避免使用它作为你的ActionListener,因为这意味着你可能让你的GUI类实现一个ActionListener,它要求穷人做太多事情,做太多。使用匿名内部类或者更好地使用AbstractActions,你会好得多。
#1
5
Yes, it makes no sense to pass an object, this
, into an array index which expects an int, not your GUI object, so I'm not sure what you were trying to achieve with this.
是的,将一个对象传递给一个需要int而不是GUI对象的数组索引是没有意义的,所以我不确定你试图通过它实现什么。
Just get a reference to the JButton that's been clicked from the ActionEvent's getSource()
method:
只需获取从ActionEvent的getSource()方法中单击的JButton的引用:
JButton btn = (JButton)e.getSource();
btn.setText("I've been clicked");
Edit:
Also you should avoid using this
as your ActionListener since this means that you're likely having your GUI class implement an ActionListener which is asking the poor class to be too many things, to do too much. You're much better off either using anonymous inner classes or else even better use AbstractActions.
编辑:你也应该避免使用它作为你的ActionListener,因为这意味着你可能让你的GUI类实现一个ActionListener,它要求穷人做太多事情,做太多。使用匿名内部类或者更好地使用AbstractActions,你会好得多。