Ответ 1
попробуйте это
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
У меня есть мои кнопки, которые работают правильно, и я слушаю каждую кнопку следующим образом:
for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
Здесь, как вы видите, вызывается слушатель, и я хочу узнать, какую кнопку я нажимаю. Есть ли способ сделать это?
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getSource());
}
};
Мне нужен способ найти кнопку в массиве.
попробуйте это
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
ActionEvent имеет метод getActionCommand(), который получит JCutton actionCommand String. Обычно это текст (для JButtons).
Чтобы получить метку, попробуйте это.
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
String label = button.getLabel(); //Deprecated
String label2 = button.getText();
}
};
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
l1.setText("");//name of level what you want
t1.setText(null);//text field what you want
t2.setText(null);//text field what you want
}