How to use an action listener to check if a certain button was clicked?

前端 未结 3 860
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 15:25

I have 4 lists of buttons arranged into a column in my program. As of now I have 4 loops that check to see if a button has been clicked or not. Is there a simple way to chec

相关标签:
3条回答
  • 2020-12-01 16:02

    Use anonymous inner classes for each button:

    JButton button = new JButton("Do Something");
    button.addActionListener( new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Do Something Clicked");
        }
    });
    

    Or if your logic is related, then you can share a listener:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class ButtonCalculator extends JFrame implements ActionListener
    {
        private JButton[] buttons;
        private JTextField display;
    
        public ButtonCalculator()
        {
            display = new JTextField();
            display.setEditable( false );
            display.setHorizontalAlignment(JTextField.RIGHT);
    
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout( new GridLayout(0, 5) );
            buttons = new JButton[10];
    
            for (int i = 0; i < buttons.length; i++)
            {
                String text = String.valueOf(i);
                JButton button = new JButton( text );
                button.addActionListener( this );
                button.setMnemonic( text.charAt(0) );
                buttons[i] = button;
                buttonPanel.add( button );
            }
    
            getContentPane().add(display, BorderLayout.NORTH);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH);
            setResizable( false );
        }
    
        public void actionPerformed(ActionEvent e)
        {
            JButton source = (JButton)e.getSource();
            display.replaceSelection( source.getActionCommand() );
        }
    
        public static void main(String[] args)
        {
            UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
            ButtonCalculator frame = new ButtonCalculator();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        }
    }
    
    0 讨论(0)
  • 2020-12-01 16:05

    Any time you click a button, it triggers the actionPerformed method, regardless of which button you pressed.

    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source instanceof JButton) System.out.println("You clicked a button!");
    }
    
    0 讨论(0)
  • 2020-12-01 16:06

    You can add an individual listener for each button and one common listener to every button. Program the common listener to respond to "any button pressed".

    0 讨论(0)
提交回复
热议问题