带有actionPerformed和keyReleased的JButton

时间:2014-04-10 12:23:36

标签: java swing jbutton actionlistener

我有一个JButton,我希望它在按下按钮时执行某些操作,并且我希望它在按下按键时执行相同的操作,我该怎么做?

5 个答案:

答案 0 :(得分:2)

要在按下按钮时执行某些操作,您应该向该按钮添加ActionListener,如下所示:

JButton button = new JButton();
button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
});

对按键的响应按这样做:(例如,如果用户输入控制alt 7)

Action actionListener = new AbstractAction() {
  public void actionPerformed(ActionEvent actionEvent) {
    JButton source = (JButton) actionEvent.getSource();
    System.out.println("Activated: " + source.getText());// just for test
  }
};
//.....

KeyStroke controlAlt7 = KeyStroke.getKeyStroke("control alt 7");
InputMap inputMap = button.getInputMap();
inputMap.put(controlAlt7, ACTION_KEY);
ActionMap actionMap = button.getActionMap();
actionMap.put(ACTION_KEY, actionListener);

答案 1 :(得分:1)

据我所知(在几年内没有与Swing混淆......)唯一可以作用于按钮的关键按钮事件是Tab,它会改变元素焦点,{ {1}}会触发Enter方法和助记符,这也会触发actionPerformed

要处理按钮点击事件,您可以执行以下操作:

actionPerformed

答案 2 :(得分:1)

您可能需要查看Action API。您可以在How to Use Actions查看更多信息。您可以使用Action按钮(类似于ActionListener),并可以为其添加关键快捷键。

您可以看到this example,其中关键快捷方式添加到工具栏按钮以及菜单项。你想要注意的有趣的事情是菜单项和工具栏按钮共享相同的Action,因此做同样的事情。

enter image description here

答案 3 :(得分:0)

    JButton button = new JButton("Submit");
    //Add action listener to button
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            //do your work here
            System.out.println("You clicked the submit button");
        }
    });      

这是如何将actionlistener与jbutton一起使用

答案 4 :(得分:0)

试试这个:

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

public class EventedButtonExample extends JFrame {
    private JButton simpleButton;
    private static final long serialVersionUID = 42L;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                EventedButtonExample me = new EventedButtonExample();
                me.initialize();
                me.setVisible(true);
            }
        });
    }

    void initialize() {
        simpleButton = new JButton("I am an simple, evented button!");
        CompoundEventHandler eh = new CompoundEventHandler();
        simpleButton.addActionListener(eh);
        simpleButton.addKeyListener(eh);
        getContentPane().add(simpleButton, BorderLayout.CENTER);
        pack();
    }

    class CompoundEventHandler extends KeyAdapter implements ActionListener {
        public void keyReleased(KeyEvent e) {
            int keyCode = e.getKeyCode();
            System.out.println("Key pressed: " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")");
        }

        public void actionPerformed(ActionEvent e) {
            System.out.println("A button is pressed!");
        }
    }
}