Search code examples
javaswingevent-handlingjbuttonactionlistener

JButton array ActionListener


In short, I would like to accumulate a bunch of JButton's to an array, and create one ActionListener class for the array.

I'm trying to create a calculator, and all the numbered buttons, such as "6", are in a JButton array, because I would like to have it input the set number into a temporary int, and it would be easier to create one method, instead of 10. I also have 40 other buttons, that I would like to apply the same principal to, but in a different array, so it would be much faster and easier to put these into a couple of ActionListener methods where the buttons data is implemented to that method. this is the code I have:

private JButton num0, num1, num2, num3, num4, num5, num6, num7, num8, num9;
private JButton numArray[] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};

        public GUI(){
          numArray.AddActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent event){

             }
       });
  }

Solution

  • You can consider the proposal of Newb Monad. However, you can use the same listener for all your buttons, as in the following example.

    public static void main(String[] args) {
    
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() instanceof JButton) {
                    String text = ((JButton) e.getSource()).getText();
                    JOptionPane.showMessageDialog(null, text);
                }
            }
        };
    
        JPanel panel = new JPanel(new GridLayout(4,3));
    
        JButton[] array = new JButton[10];
        for (int i = 0; i < array.length; i++) {
            array[i] = new JButton(String.valueOf(i));
            array[i].addActionListener(listener);
            panel.add(array[i]);
        }
    
        JOptionPane.showMessageDialog(null, panel);
    
    }
    

    Dialog

    Event