gpt4 book ai didi

java - 遍历一组复选框

转载 作者:行者123 更新时间:2023-12-01 15:15:38 25 4
gpt4 key购买 nike

如何在 Swing 中使用键盘箭头键遍历一组复选框?

注意:复选框放置在网格布局中

最佳答案

以下是基于 How to Use the Focus Subsystem 的示例将向右和向后箭头注册为向前和向后焦点遍历键的教程。

import java.awt.AWTKeyStroke;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class CheckBoxDemo {

private static void createAndShowGUI() {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new GridLayout(2, 2, 10, 10));

frame.add(new JCheckBox("Bird"));
frame.add(new JCheckBox("Cat"));
frame.add(new JCheckBox("Dog"));
frame.add(new JCheckBox("Rabbit"));

Set<AWTKeyStroke> forwardKeys = frame.getFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
Set<AWTKeyStroke> newForwardKeys = new HashSet<AWTKeyStroke>(forwardKeys);
newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
frame.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);

Set<AWTKeyStroke> backwardKeys = frame.getFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
Set<AWTKeyStroke> newBackKeys = new HashSet<AWTKeyStroke>(backwardKeys);
newBackKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
frame.setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, newBackKeys);

frame.pack();
frame.setVisible(true);

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

关于java - 遍历一组复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11644126/

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