In my custom JFileChooser
, I want to get the Open button, so I am using the following code:
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;
}
The problem with this code is that it is inefficient (because of recursion) and also can be broken if localization is used (because the word "Open" is hard-coded).
I also want to get the JTextField
in which the user can enter the name and path of a file. I am using this code to get this component:
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;
}
Is there a better way I can get the Open button and the JTextField
?
In the constructor of my custom file chooser, I called the setApproveButtonText
method and passed in a custom string to use for the Open button. I called this method before I get the Open button using the getOpenButton
method below. This way, I am guaranteed to get the Open button on any OS platform and no matter what locale the JVM is using.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.