我有一个像这样的选项对话框:
String[] options = ["Yes", "No"]; //button names
int n = JOptionPane.showOptionDialog(singleFrameService.getFrame(),
"Some Question?",
"",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
//if press yes
if (n == JOptionPane.YES_OPTION){
//make some if pressed Yes
}
当我使用鼠标并按是/否时 - 一切正常...... 但是当我开始使用键盘时,按TAB转到“否”按钮,然后按ENTER键 - 工作“是”选项
答案 0 :(得分:11)
这将使uimanager处理聚焦按钮。这将允许您使用输入或空格来选择聚焦按钮。
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
答案 1 :(得分:9)
这完全取决于外观'AFAIK。在L& F中,“输入”表示“按默认按钮”(即是)。可以通过按空格键来按下聚焦按钮。
答案 2 :(得分:1)
我需要JOptionPane以响应空格键的方式响应返回键,这就是我成功实现它的方式: 我创建了一个新的JOPtionPane实例,并调用其createDialog方法来获取它的对话窗口。
然后我将它的对话框窗口传递给下面的listComponents(java.awt.Container)方法,这样做了!
private static index=0;
private static void listComponents(java.awt.Container c){
if(c==null)return;
for(java.awt.Component cc:c.getComponents())
listComponents((java.awt.Container)cc);
if(c instanceof javax.swing.JButton){
buttons[index++]=(javax.swing.JButton)c;
javax.swing.InputMap inputMap=buttons[index-1].getInputMap(javax.swing.JComponent.WHEN_FOCUSED);
javax.swing.Action spaceAction=buttons[index-1].getActionMap().get(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SPACE,0));
inputMap.put(javax.swing.KeyStroke
.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,0),spaceAction);
}
}
答案 3 :(得分:0)
除了JB Nizet的回答之外,我想提一下,如果我理解的话,java中的输入处理会这样:
所有这些都与它们的添加顺序相反(我不是100%关于这一点,但这是合乎逻辑的)。现在,inputEvent可以消费。在这种情况下,JOptionPane注册 enter ,并遍历具有绑定到输入事件的操作的组件集合。 yes
按钮,默认按钮消耗此事件,以便其他任何组件都无法对其执行任何操作。
您的问题的解决方案是您将不得不创建自定义JDialog。给它一个消息标签,一个图标占位符和两个按钮。现在使用与您正在使用的JOptionPane相同的构造函数,并根据构造函数接收的参数为每个组件提供文本/图标。
答案 4 :(得分:0)
除了JB Nizet的回答之外,我想建议您是否不能使用ENTER
键来访问Yes, No
按钮而不是尝试禁用该密钥。这里有一些例子:
public class NewClass {
public static void main(String[] args) {
JFrame frame = new JFrame();
String[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(frame,
"Some Question? Press space bar to continue...",
"",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
null); // disabled the ENTER Key
System.out.println(n);
if (n == JOptionPane.YES_OPTION) {
System.out.println("Yes");
} else {
System.out.println("No");
}
System.exit(1);
}
}