使用KeyBIndings响应Button [英] Responding to Button using KeyBIndings

查看:137
本文介绍了使用KeyBIndings响应Button的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个具有以下目标的程序:

I want to make a program with these goals:

1)制作一个JButton
2)将按钮附加到一个键(A Key)使用KeyBindings
3)点击A时执行一些代码

1) Make a JButton 2) Attach the button to a key (The "A" Key) using KeyBindings 3) Execute some code when "A" is clicked

这是我到目前为止的代码:

Here is the code I have so far:

// Imports

Public class Test{

JButton button = new JButton();

//...

Test(){

button.getInputMap().put(KeyStroke.getKeyStroke("A"), "Pressed");


//...

}

// Where do I add the code that responds when button is pressed?
}

现在我在哪里添加我希望它在按钮时执行的代码被按下了吗?

Now where do I add the code that I want it to execute when the button is pressed?

推荐答案

你需要添加一个动作监听器,具体针对actionPerformed。在构造函数中的某处声明:

you need to add an action listener, specificaly for actionPerformed. declare this somewhere inside your constructor:

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

public class Main {
    public static void main(String[] argv) throws Exception {

        JButton component = new JButton();
        MyAction action = new MyAction();
        component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
            action.getValue(Action.NAME));
    }
}

class MyAction extends AbstractAction {
    public MyAction() {
        super("my action");
    }

    public void actionPerformed(ActionEvent e) {
        //Here goes the code where the button does something
        System.out.println("hi");//In this case we print hi
    }
}

在此例如,如果按F2键,则相当于按下按钮。

In this example if we press F2 it will be the equivalent of pressing the button.

这篇关于使用KeyBIndings响应Button的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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