本文介绍了如何设置Java默认按钮在ENTER键_released_上做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,我使用默认按钮。 ENTER
Key is release 。 $ ENTER
键是 。 我删除了 KeyStroke
从 InputMap
的按钮。但它对我来说并不奏效我应该怎么做?
import javax.swing。*;
import java.awt。*;
import java.awt.event.ActionEvent;
public class ButtonTest {
public static void main(String [] args){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
buildFrame();
}
});
}
private static void buildFrame(){
JFrame f = new JFrame(Test);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button = new JButton(new AbstractAction(Button){
@Override
public void actionPerformed(ActionEvent e){
System.out.println ButtonTest :: actionPerformed:CALLED);
}
});
JButton button2 = new JButton(Button 2);
InputMap im = button.getInputMap();
im.put(KeyStroke.getKeyStroke(ENTER),none);
im.put(KeyStroke.getKeyStroke(released ENTER),released);
f.setLayout(new GridBagLayout());
f.add(button);
f.add(button2);
f.getRootPane()。setDefaultButton(button);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
这是示例代码。
解决方案
JRootPane rootPane = SwingUtilities.getRootPane(/ *您的JButton * /);
rootPane.setDefaultButton(/ *您的JButton * /);
In my application I use a Default button. I want it to react when ENTER
Key is released. Not when ENTER
Key is pressed.
I removed the KeyStroke
from InputMap
of the button. But it didn't work for me. How should i do that?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
buildFrame();
}
});
}
private static void buildFrame() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Button") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ButtonTest::actionPerformed: CALLED");
}
});
JButton button2 = new JButton("Button 2");
InputMap im = button.getInputMap();
im.put(KeyStroke.getKeyStroke("ENTER"), "none");
im.put(KeyStroke.getKeyStroke("released ENTER"), "released");
f.setLayout(new GridBagLayout());
f.add(button);
f.add(button2);
f.getRootPane().setDefaultButton(button);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
This is the sample code.
解决方案
JRootPane rootPane = SwingUtilities.getRootPane(/* Your JButton */);
rootPane.setDefaultButton(/* Your JButton */);
这篇关于如何设置Java默认按钮在ENTER键_released_上做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!