Java – attach a single action listener to all buttons

I have a program with many buttons, all of which will perform the same function I wonder if there is a way to attach a single listener to all the existing jbuttons in the program

Solution

It's like:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display,BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0,5) );
        add(buttonPanel,BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50,50) );
            buttonPanel.add( button );

            Keystroke pressed = Keystroke.getKeystroke(text);
            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(pressed,text);
            button.getActionMap().put(text,numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin",new Insets(10,10,10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloSEOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokelater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

The action gets the source object from the event so that it knows which button was clicked

If you need to use if / else logic in an action, you should create a separate action If the code does not belong to an action, please do not enforce it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>