Now I am writing a calculator, here is a small question:
I create buttons from an array of strings (so that they don't take up much space)

String [] buttonName = {"1","2","3","/","4","5","6","*","7","8","9","+","0","-","C","="}; for (String string : buttonName) { panel2.add(new JButton(String.valueOf(string))); } 

How, in this case, to add an ActionListener to each button?

    3 answers 3

    Well, there are different ways. But in general this is done in this spirit.

     public class Test { JPanel panel2 = new JPanel(); void test() { String[] buttonName = {"1", "2", "3", "/", "4", "5", "6", "*", "7", "8", "9", "+", "0", "-", "C", "="}; for (String string : buttonName) { panel2.add(createButton(string)); } } private JButton createButton(String string) { JButton btn = new JButton(string); btn.addActionListener(new CalcButtonActionListener(string)); return btn; } } class CalcButtonActionListener implements ActionListener { private final String buttonName; public CalcButtonActionListener(String buttonName) { this.buttonName = buttonName; } public void actionPerformed(ActionEvent e) { // do something with digit or action } } 
    • mmm thanks, I'll try now) then accomplish my goal;) - Kobayashi_Maru
      final List < String > buttons = new LinkedList < String > (); buttons.add ( "this" ); buttons.add ( "is" ); buttons.add ( "a" ); buttons.add ( "test" ); final JFrame frame = new JFrame (); for ( final String name : buttons ) { final AbstractAction a = new AbstractAction ( name ) { @Override public void actionPerformed ( final ActionEvent e ) { System.out.println ( this ); } }; frame.add ( new JButton ( a ) ); } 
    • Interesting code conventions for java. - angry

    I found this solution:

     for (Component comp : panel2.getComponents()) { if (comp instanceof JButton) { ((JButton)comp).addActionListener(new CalcButtonListener()); } }