如何在使用JButton时重用actionListener的按键方法?

时间:2016-02-04 14:49:59

标签: java swing jbutton windowbuilder

我正在用Java创建一个计算器GUI应用程序。我用鼠标在JButtons上实现了压力计算器。我想听一下数字小键盘,但我不想在ActionListener中重新创建方法。

例如,这是我在JButton上按下时实现listenOne的方式。

class ListentoOne implements ActionListener{
        public void actionPerformed(ActionEvent arg) {

            if(floating)
                aftDec+="1";

            else if(!operanD)
                ans=(ans*10)+1;

            else
            operand=(operand*10)+1;

            screen.setText(output+="1");

            }
}

在面板类的构造函数中,我用这种方式构造了JButton:

one=new JButton("1");
one.addActionListener(new ListentoOne());

3 个答案:

答案 0 :(得分:4)

我会使用Key Bindings,而不是KeyListener。当然,使用Key Bindings有多种方法可以实现这一点,但在我的示例中,如果按doClick(),我会在按钮上调用1创建新课程。

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;

public class Example {

    public Example() {

        JLabel label = new JLabel("0");
        ShortCutButton button = new ShortCutButton("1", KeyStroke.getKeyStroke(KeyEvent.VK_1, 0));
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(String.valueOf(Integer.parseInt(label.getText()) + 1));
            }
        });
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        frame.add(button);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Example();
            }
        });
    }

    public class ShortCutButton extends JButton {
        public ShortCutButton(String text, KeyStroke keyStroke) {
            setText(text);
            getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "42");
            getActionMap().put("42", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    doClick();
                }
            });
        }
    }

}

答案 1 :(得分:0)

for(ActionListener a: button.getActionListeners()) {
    a.actionPerformed(yourActionEvent);
}

答案 2 :(得分:0)

查看Calculator Panel示例。

它显示了如何为所有按钮共享一个ActionListener。该示例还使用KeyBindings,以便您可以单击按钮或键入按钮上显示的数字以调用操作。