如何使用动作侦听器检查是否单击了某个按钮? [英] How to use an action listener to check if a certain button was clicked?

查看:77
本文介绍了如何使用动作侦听器检查是否单击了某个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有4个按钮列表,排列成一列。截至目前,我有4个循环来检查是否已单击按钮。有没有一种简单的方法来检查是否已单击任何按钮,而不是循环浏览每个列表以查看是否已单击该特定按钮。必须有一种更简单的方法来检查 actionSource == anybutton ...

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 check if any button has been clicked instead of looping through each list to see if that certain button was clicked. There must be an easier way to check if "actionSource == anybutton"...

推荐答案

为每个按钮使用匿名内部类:

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);
    }
}

这篇关于如何使用动作侦听器检查是否单击了某个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆