gpt4 book ai didi

java - 如何更改 JComboBox 和 JButton 的默认输入

转载 作者:行者123 更新时间:2023-12-02 02:51:09 25 4
gpt4 key购买 nike

如何让 Enter 键触发 GUI 中的 JComboBox 或 JButton,而不必按空格键?我有各种各样的文本字段和复选框,中间有按钮和组合框。我希望避免在按空格键和 Enter 键之间切换,而只需按 Enter 键即可访问所有组件。

package koning.personal.dungeonsanddragons;

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

public class test {

JFrame window = new JFrame("testGUI");
JPanel windowPanel = new JPanel();

public static JLabel labelSize;
public static JComboBox<String> comboSize;

public static JLabel labelButton;
public static JButton buttonButton;

public test () {
super();

labelSize = new JLabel("Monster Size:");
String[] sizeChoices = { "None", "Tiny", "Small", "Medium", "Large", "Huge", "Colossal"};
comboSize = new JComboBox<String>(sizeChoices);
comboSize.setToolTipText("The creature's size.");

labelButton = new JLabel("Button:");
buttonButton = new JButton();

windowPanel.setLayout(new FlowLayout());
windowPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
windowPanel.add(labelSize);
windowPanel.add(comboSize);
windowPanel.add(labelButton);
windowPanel.add(buttonButton);
windowPanel.setVisible(true);

window.setSize(500, 500);
window.setLayout(new FlowLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.add(windowPanel);

comboSize.addActionListener(handler);
buttonButton.addActionListener(handler);
}

ActionHandler handler = new ActionHandler();
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent eventFocus){
if (eventFocus.getSource() == comboSize){
buttonButton.requestFocusInWindow();
}
if (eventFocus.getSource() == buttonButton){
comboSize.requestFocusInWindow();
}
}
}

@SuppressWarnings("unused")
public static void main(String[] args) {
test GUITest = new test();
}

}

最佳答案

您可以添加一个KeyListener并执行doClick

JButton btn = new JButton();
btn.addKeyListener(new KeyListener() {

@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
btn.doClick();

}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub

}
});

关于java - 如何更改 JComboBox 和 JButton 的默认输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43830008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com