JFileChooser: set the name text field not enabled

大城市里の小女人 提交于 2019-12-13 02:57:53

问题


I'm using a JFileChooser to let the user save a file. But I don't want the user to choose a name, for the file to save. The name text field must be not enabled.

I read the doc and I did not find a such method or property.


回答1:


Squiddie in comments recommends you a good solution. However if still want to disable the textfield, so the name of the file is visible to the user (with JFileChooser.DIRECTORIES_ONLY it is not), you can use the following code in order to "grab" the textfield from the chooser and disable it.

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class TextFieldFromFileChooser {
    public TextFieldFromFileChooser() {
        JFileChooser chooser = new JFileChooser();
        JTextField fileChooserTextField = getFileChooserTextField(chooser);
        fileChooserTextField.setText("I name this file.txt");
        fileChooserTextField.setEditable(false);
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            // Selected file has the name of the fileChooserTextField' text
            System.out.println(chooser.getSelectedFile().getAbsolutePath());
        }
    }

    private static JTextField getFileChooserTextField(JFileChooser chooser) {
        JTextField f = null;
        for (Component c : getComponents(chooser)) {
            if (c instanceof JTextField){
                f = (JTextField) c;
                break;
            }
        }
        return f;
    }

    private static List<Component> getComponents(JComponent component) {
        List<Component> list = new ArrayList<>();
        for (Component c : component.getComponents()) {
            if (c instanceof JPanel)
                list.addAll(getComponents((JPanel) c));
            else if (c instanceof JTextField)
                list.add((JTextField) c);
        }
        return list;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TextFieldFromFileChooser());
    }
}

Note that this has been tested with Windows LAF and java's stock LAF. If your chooser has 2 textfields (i have no idea how is on MAC/linux), you might have a problem because you do not know which of the textfields you disable.



来源:https://stackoverflow.com/questions/54251586/jfilechooser-set-the-name-text-field-not-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!