回车切换焦点问题,如何将Tab键功能用Enter实现?
使用Java Swing设计的JFrame,画面中有很多类型的控件,如JTextField, JComboBox, JButton,
JCheckBox等,默认支持Tab键切换控件焦点,切换顺序按照控件所处位置从左到右,从上到下进行,现在
我想修改这种默认设置,要求:
(1) 用Enter键代替Tab键执行控件焦点切换;
(2) 想自己定义控件焦点切换的顺序,即自己定义控件切换规则;
(3) 因为画面中我要控制有些情况下某些控件不可用,即setEnabled(false),所以切换焦点时,在(2)定
义规则的前提下,可以自动跳过这些不可用的控件,切换到可用的控件,如何实现呢?用Tab键切换时就
可以自动跳过那些不可用的控件,它是怎么实现的呢?
高手能否指点一二,非常感谢!
希望各位大虾能提出宝贵意见,本人不甚感激,并有分数送上!
------解决方案--------------------import java.awt.*;
import java.awt.event.*;
public class MyTextField extends TextField {
MyTextField(int len) {
super(len);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
transferFocus();}});
}
}
====================================
看看好使吗?
------解决方案--------------------判断是否是回车键的码,是的话转移焦点。
------解决方案--------------------import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
/**
* 鼠标事件监听。监听回车和上下箭头。回车和下箭头到下一组件,上箭头到上一组件
*
* @author marvy
*/
public class ComponentFocusKeyAdapter extends KeyAdapter {
// 当前组件
private JComponent currentFocusComponent = null;
// 上一组件
private JComponent preFocusComponent = null;
// 下一组件
private JComponent nextFocusComponent = null;
public ComponentFocusKeyAdapter() {
super();
}
/**
* 构造监听组件
*
* @param preFocusComponent 上一组件
* @param nextFocusComponent 下一组件
*/
public ComponentFocusKeyAdapter(JComponent preFocusComponent,
JComponent currentFocusComponent, JComponent nextFocusComponent) {
this.preFocusComponent = preFocusComponent;
this.currentFocusComponent = currentFocusComponent;
this.nextFocusComponent = nextFocusComponent;
}
/**
* 键释放操作
*
* @see java.awt.event.KeyAdapter#keyReleased(java.awt.event.KeyEvent)
*/
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
// 下一个聚焦组件不为空
if (nextFocusComponent != null) {
// 回车
if (e.getKeyCode() == 10) {
nextFocusComponent.requestFocus();
return;
}
// 如果是下拉框或列表
if (currentFocusComponent instanceof JComboBox
|| currentFocusComponent instanceof JList) {
// 右箭头
if (e.getKeyCode() == 39) {
nextFocusComponent.requestFocus();
return;
}
}
// 下箭头
if (e.getKeyCode() == 40) {
nextFocusComponent.requestFocus();
return;
}
}
// 下一个聚焦组件不为空
if (preFocusComponent != null) {
// 如果是下拉框或列表
if (currentFocusComponent instanceof JComboBox
|| currentFocusComponent instanceof JList) {
// 左箭头
if (e.getKeyCode() == 37) {
preFocusComponent.requestFocus();