[英]Getting the Open button and JTextField in a JFileChooser?
在我的自定义JFileChooser
,我想要获取“打开”按钮,因此我正在使用以下代码:
private static JButton getOpenButton(Container c) {
Validator.checkNull(c);
int len = c.getComponentCount();
JButton button = null;
for (int index = 0; index < len; index++) {
if (button != null) {
break;
}
Component comp = c.getComponent(index);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
if ("Open".equals(b.getText())) {
return b;
}
}
else if (comp instanceof Container) {
button = getOpenButton((Container) comp);
}
}
return button;
}
该代码的问题在于它效率低下(由于递归),并且如果使用本地化也可能被破坏(因为单词“ Open”是硬编码的)。
我还想获取用户可以在其中输入文件名和路径的JTextField
。 我正在使用此代码来获取此组件:
private static JTextField getTextField(Container c) {
Validator.checkNull(c);
int len = c.getComponentCount();
JTextField textField = null;
for (int index = 0; index < len; index++) {
if (textField != null) {
break;
}
Component comp = c.getComponent(index);
if (comp instanceof JTextField) {
return (JTextField) comp;
}
else if (comp instanceof Container) {
textField = getTextField((Container) comp);
}
}
return textField;
}
有没有更好的方法可以获取“打开”按钮和JTextField
?
在自定义文件选择器的构造函数中,我调用了setApproveButtonText
方法,并传入了自定义字符串以用于“打开”按钮。 在使用下面的getOpenButton
方法获取“打开”按钮之前,我先调用了此方法。 这样,无论JVM使用哪种语言环境,都可以确保在任何操作系统平台上都可以使用“打开”按钮。
private final String title;
public CustomFileChooser(String title) {
this.title = title;
setApproveButtonText(title);
this.button = getOpenButton(this);
}
private JButton getOpenButton(Container c) {
Validator.checkNull(c);
int len = c.getComponentCount();
JButton button = null;
for (int index = 0; index < len; index++) {
if (button != null) {
break;
}
Component comp = c.getComponent(index);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
if (this.title.equals(b.getText())) {
return b;
}
}
else if (comp instanceof Container) {
button = getOpenButton((Container) comp);
}
}
return button;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.