That's all. Code: UPD:

public class Standart implements ActionListener{ JButton But1; Standart(String name, String size){ JFrame jfrm=new JFrame(name); JButton But1=new JButton("B1"); But1.addActionListener(this); jfrm.add(But1,BorderLayout.CENTER); jfrm.pack(); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrm.setVisible(true); But1.setBorderPainted(true); But1.setBackground(Color.YELLOW); } public void actionPerformed(ActionEvent ae){ if(ae.getActionCommand().equals("B1")){ But1.setText("Pressed"); } } public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ new Standart("reb","ver"); } }); } 

}

    1 answer 1

    Maybe you need to replace

     if(ae.getActionCommand().equals("B1")){ 

    on

     if(ae.getText().equals("B1")){ 

    UPD0.

    The final result and debriefing:

     public Standard(String name, String size){ JFrame jfrm=new JFrame(name); But1=new JButton("B1"); // тут вы объявляли локальную переменную JButton But1, она перекрывала видимость поля But1 самого объекта But1.addActionListener(this); //Да, неплохо бы прикрепить к кнопке обработчик; то что у вас есть метод actionPerformed еще не значит, что туда будут отправляться события. Сам класс Standart должен имплементировать интерфейс ActionListener. jfrm.add(But1,BorderLayout.CENTER); jfrm.pack(); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrm.setVisible(true); } public void actionPerformed(ActionEvent ae){ // впрочем тут сработает и ваш вариант с getActionCommand() if(((JButton)ae.getSource()).getText().equals("B1")){ But1.setText("Pressed"); // does nothing } } 
    • Doesn't work anyway - dddkk
    • one
      @iamqwerty, updated the answer. - Nofate
    • How was it possible to forget to attach the handler ?! Thanks, I will try - dddkk
    • one
      Once again: note the line: JButton But1 = new JButton ("B1"); and how it is written for me: But1 = new JButton ("B1"); In your case, you hang the handler on a button stored in a local constructor variable. And in the handler, set the text to the button stored in the class field (which is not initialized, and obviously, you get an NPE ). - Nofate
    • Thanks, it turned out - dddkk