我正在尝试构建一个使用3x3网格按钮(使用Java Swing)的程序,因此我使用GridLayout和循环来初始化它以创建按钮:
panel.setBorder(BorderFactory.createEmptyBorder(3,3,5,5))
panel.setLayout(new GridLayout(3,3,10,10));
String[] buttons = {"Top Left", "Top Middle", "Top Right", "Middle Left", "Middle", "Middle Right", "Bottom Left", "Bottom Middle", "Bottom Right"};
for(int i = 0; i < buttons.length; i++) {
buttray[i] = new JButton(buttons[i]);
panel.add(buttray[i]);
buttray[i].addActionListener(this);
}
按钮加载得很好,但我不明白如何使用ActionListeners来区分按钮。当我从打印输出中检查paramString()方法时,每个按钮都提供相同的修饰符:
Top Left
ACTION_PERFORMED,cmd=Top Left,when=1431640106712,modifiers=Button1
Top Middle
ACTION_PERFORMED,cmd=Top Middle,when=1431640107566,modifiers=Button1
Top Right
ACTION_PERFORMED,cmd=Top Right,when=1431640107978,modifiers=Button1
此修饰符值是否作为按钮的标识符,如果是,我该如何更改?
答案 0 :(得分:3)
有多种方法可以区分触发ActionEvent的按钮:
if (e.getActionCommand().equals("Top Left")
)if (e.getSource() == buttray[0] )
)if (e.getSource().getText().equals("Top Left")
)if (e.getSource().getName().equals("Top Left")
)答案 1 :(得分:1)
你已经通过数组索引跟踪按钮,即buttray [i]。使用getSource()
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
for(int i=0;i<buttray.length;i++)
if(e.getSource()==buttray[i])
{
//code here
}
}