2013-01-10 23 views
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

+0

*「有沒有更好的方法..?」*有*理由*來擴展JFileChooser嗎?如果是這樣,那是什麼? –

+0

我擴展了我的'JFileChooser',因爲我想根據某些條件啓用或禁用Open按鈕。在另一個線程上檢查條件,一旦完成,EDT將更新「打開」按鈕的啓用狀態。 –

+0

不,並且(我會建議)它在整個平臺上都不可靠。更好地推出自己的(不幸) – MadProgrammer

回答

0

在我的自定義文件選擇器的構造函數中,我調用了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; 
}