class toolButton extends JButton {
toolButton(String name, int i) {
super(name);
this.index = i;
}
public int getSelectionIndex() {
return this.index;
}
private int index;
}
生成我的按钮列表的方法:
public void showItemList(ArrayList<Item> arrayList) {
for (int i = 0; i < arrayList.size(); i++) {
toolButton but = new toolButton(arrayList.get(i).getName()", i); //getName() returns the name of the Item to be displayed
this.add(but);
but.addMouseListener(new MouseAdapter() {
// Simple anonymous class for the listener
public void mousePressed(MouseEvent e) {
selected = but.getSelectionIndex(); //This sets the index number in the class that uses this method
}
});
}
}
至少我在做什么。但是我想知道是否有一种更好的方法,还是至少可以接受,如果它完全没有皱眉。我认为在这种情况下,在ActionEvent上使用GetSource()不会有很大的用处。而且我真的不能为每个按钮写一个听众,因为我不知道有多少个按钮。Edit: 我要建模的是一个简单的分配器,分配器包含一系列物品(每个项目都有名称和价格)。分配器类具有“购买(项目项目)”的方法。因此,我要做的是让一个按钮表示分配器中的每个可用项目,当按下按钮时,我希望对项目的引用传递给方法(项目)(该按钮不必调用买入(项目)方法本身)。 据我确定您了解,这是一项课堂练习,所以我无法更改要求。
如果ArrayList参数中的项目名称足以解析相应的项目类别,则您不必为jbutton子类别,但可以按照以下方式使用它:
public void showItemList(ArrayList<Item> arrayList){
for(int i = 0; i < arrayList.size(); i++){
JButton but = new JButton(arrayList.get(i).getName());
getContentPane().add(but);
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
String itemName = event.getActionCommand();
}
});
}
}
一些注释:
在您的情况下,您应该使用ActionListener而不是Mouselistener。作为附加值,您可以查询单击按钮的标签:event.getActionCommand(),因此您知道选择了哪个项目,并且不必实现子类以跟踪索引。