0
在我的自定義JFileChooser
,我想打開按鈕,所以我用下面的代碼:獲取JFileChooser中的打開按鈕和JTextField?
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;
}
這段代碼的問題是,它是低效的(因爲遞歸),也可破如果使用本地化(因爲「打開」一詞是硬編碼的)。
我也想得到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
?
*「有沒有更好的方法..?」*有*理由*來擴展JFileChooser嗎?如果是這樣,那是什麼? –
我擴展了我的'JFileChooser',因爲我想根據某些條件啓用或禁用Open按鈕。在另一個線程上檢查條件,一旦完成,EDT將更新「打開」按鈕的啓用狀態。 –
不,並且(我會建議)它在整個平臺上都不可靠。更好地推出自己的(不幸) – MadProgrammer