作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 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/
我是一名优秀的程序员,十分优秀!