Dal*_*son 7 java user-interface swing
对于我使用过的大多数GUI,当包含文本的控件获得焦点时,将选择控件的全部内容.这意味着如果您刚开始输入,则完全替换以前的内容.
示例:您具有使用零值初始化的旋转控件.您选中它并键入"1"控件中的值现在为1.
使用Swing,这不会发生.未选择控件中的文本,克拉显示在现有文本的一端或另一端.继续上面的例子:
使用Swing JSpinner,当您选择旋转控件时,克拉位于左侧.键入"1",控件中的值现在为10.
这驱使我(和我的用户)爬上墙,我想改变它.更重要的是,我想全局更改它,因此新行为适用于JTextField,JPasswordField,JFormattedTextField,JTextArea,JComboBox,JSpinner等.我发现这样做的唯一方法就是为每个控件添加一个FocusAdapter,并将focusGained()方法覆盖为Do The Thing [tm].
必须有一种更简单,更不易碎的方式.请?
编辑:此特定案例的另一条信息.我正在使用的表单是使用Idea的表单设计器生成的.这意味着我通常不会编写代码来创建组件.有可能告诉Idea你想自己创建它们,但这是我想避免的麻烦.
座右铭:所有优秀的程序员基本都是懒惰的.
阅读到目前为止的回复后(谢谢!)我将最外面的 JPanel 传递给以下方法:
void addTextFocusSelect(JComponent component){
if(component instanceof JTextComponent){
component.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent event) {
super.focusGained(event);
JTextComponent component = (JTextComponent)event.getComponent();
// a trick I found on JavaRanch.com
// Without this, some components don't honor selectAll
component.setText(component.getText());
component.selectAll();
}
});
}
else
{
for(Component child: component.getComponents()){
if(child instanceof JComponent){
addTextFocusSelect((JComponent) child);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有用!