Как при помощи JFileChooser выбрать файл ,а путь к файлу отобразился в JtextField после закрытия диалогового окна

233
22 сентября 2018, 23:30

Как при помощи JFileChooser выбрать файл и вернуть путь к файлу в JTextField?

    JFileChooser d= new JFileChooser();
    d.showOpenDialog(this);
    File f = d.getSelectedFile();

Код показывает окно выбора файла.
А задача дальше, отобразить весь путь к файлу в JTextField.

Answer 1

Применяю ваш пример ко всей программе и никак не могу понять,что нужно!Хочу на кнопку button2 прикрепить ActionListener и не получается!Где ошибка?`

public class JFileDialogTest {
private  JButton button2 = new JButton();
private JFrame d = new JFrame("Конвертер RPC");
 private   JTextField f1 = new JTextField(25);
private   JTextField f2 = new JTextField(25);
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(() ->
        {
            JFrame d = new JFrame("Конвертер RPC");
            //JTextField textField = new JTextField();
          JTextField f1 = new JTextField(25);
          JTextField f2 = new JTextField(25); 
            JButton button = new JButton("Выбрать");
             JButton button1 = new JButton("Сохранить");
             JButton button2 = new JButton("Конвертировать");
               Component L1 = new JLabel("Файл xml");
               Component L2 = new JLabel("Файл txt");
            button.addActionListener(e -> {
                JFileChooser fileChooser = new JFileChooser();
                int res = fileChooser.showOpenDialog(d);
                if (res == JFileChooser.APPROVE_OPTION) {
                    f1.setText(fileChooser.getSelectedFile().getAbsolutePath());
                }
            });

            button1.addActionListener(e -> {
                JFileChooser fileChooser = new JFileChooser();
             //   FileNameExtensionFilter filter = new FileNameExtensionFilter("txt");
               // fileChooser.setFileFilter(filter);
                int res = fileChooser.showSaveDialog(d);
                if (res == JFileChooser.APPROVE_OPTION) {
                    f2.setText(fileChooser.getSelectedFile().getAbsolutePath());
                }
            });  
           ActionListener act = new jfiledialogtest.ClassXmlTest();                
            button2.addActionListener(act);       

             Container contentPane1 = d.getContentPane();
             SpringLayout layout = new SpringLayout();
             contentPane1.setLayout(layout);
             contentPane1.add(f1);
             contentPane1.add(f2);
             contentPane1.add(button);
             contentPane1.add(button1);
             contentPane1.add(button2);
              contentPane1.add(L1);
              contentPane1.add(L2);

    layout.putConstraint(SpringLayout.WEST , f1, 10, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, f1, 55, 
                         SpringLayout.NORTH, contentPane1);
 //   layout.putConstraint(SpringLayout.NORTH, f2, 25, 
   //                      SpringLayout.NORTH, contentPane1);
    //layout.putConstraint(SpringLayout.WEST , f1, 120, 
     //                    SpringLayout.EAST , f1      );
     layout.putConstraint(SpringLayout.WEST , f2, 10, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, f2, 150, 
                         SpringLayout.NORTH, contentPane1);
    //layout.putConstraint(SpringLayout.NORTH, f2, 75, 
      //                   SpringLayout.NORTH, contentPane1);
    //layout.putConstraint(SpringLayout.WEST , f2, 120, 
     //                    SpringLayout.EAST , f1      );
     layout.putConstraint(SpringLayout.WEST , button, 320, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, button, 50, 
                         SpringLayout.NORTH, contentPane1);
    layout.putConstraint(SpringLayout.WEST , button1, 320, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, button1, 145, 
                         SpringLayout.NORTH, contentPane1);
    layout.putConstraint(SpringLayout.WEST , button2, 150, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, button2, 250, 
                         SpringLayout.NORTH, contentPane1);
    layout.putConstraint(SpringLayout.WEST , L1, 10, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, L1, 40, 
                         SpringLayout.NORTH, contentPane1);
    layout.putConstraint(SpringLayout.WEST , L2, 10, 
                         SpringLayout.WEST , contentPane1);
    layout.putConstraint(SpringLayout.NORTH, L2, 135, 
                         SpringLayout.NORTH, contentPane1);     


          //  d.add(f1, BorderLayout.NORTH);
           // d.add(button, BorderLayout.CENTER);
            //d.pack();
            d.setSize(450, 350);
            d.setLocationRelativeTo(null);
            d.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            d.setVisible(true);
        });
           //ActionListener act = new JFileDialogTest.ClassXmlTest();                
           //button2.addActionListener(act);
}
public   class ClassXmlTest implements ActionListener {
        String str1 = f1.getText();
        String str2 = f2.getText();

    public ClassXmlTest() {            
         //String  str1 = f1.getText();
         //String str2 = f2.getText();
          File xmlFile = new File(str1);
         File txtFile = new File(str2);
        try {
            transform(xmlFile, txtFile);
        } catch (Exception e) {
            e.printStackTrace();     
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {


        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

    public static void transform(File sourceXmlFile, File targetTxtFile) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        org.w3c.dom.Document doc =  dBuilder.parse(sourceXmlFile);
        // doc.getDocumentElement().normalize();
        org.w3c.dom.Node element = doc.getElementsByTagName("RPC").item(0);
        NodeList nodeList = element.getChildNodes();
        try (FileWriter fileWriter = new FileWriter(targetTxtFile)) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                org.w3c.dom.Node node =  nodeList.item(i);
                String nodeName = node.getNodeName();
                String value = node.getTextContent();
                String lineSeparator = System.getProperty("line.separator");
                switch (nodeName) {
                    case "nLineOff":
                        write(fileWriter, "LINE_OFF", value, "pixels"+ lineSeparator);
                        break;
                    case "nSampOff":
                        write(fileWriter, "SAMP_OFF", value, "pixels"+ lineSeparator);
                        break;
                    case "nLatOff":
                        write(fileWriter, "LAT_OFF", value, "degrees"+ lineSeparator);
                        break;
                    case "nLongOff":
                        write(fileWriter, "LONG_OFF", value, "degrees"+ lineSeparator);
                        break;
                    case "nHeightOff":
                        write(fileWriter, "HEIGHT_OFF", value, "meters"+ lineSeparator);
                        break;
                    case "nLineScale":
                        write(fileWriter, "LINE_SCALE", value, "pixels"+ lineSeparator);
                        break;
                    case "nSampScale":
                        write(fileWriter, "SAMP_SCALE", value, "pixels"+ lineSeparator);
                        break;
                    case "nLatScale":
                        write(fileWriter, "LAT_SCALE", value, "degrees"+ lineSeparator);
                        break;
                    case "nLongScale":
                        write(fileWriter, "LONG_SCALE", value, "degrees"+ lineSeparator);
                        break;
                    case "nHeightScale":
                        write(fileWriter, "HEIGHT_SCALE", value, "meters"+ lineSeparator);
                        break;
                    case "bLineNum":
                        String[] array1 = value.trim().split(",");
                        for (int c = 0; c < array1.length; c++) {
                            write(fileWriter, "LINE_NUM_COEFF_" + (c + 1), array1[c], ""+ lineSeparator);
                        }
                        break;
                    case "bLineDen":
                        String[] array2 = value.trim().split(",");
                        for (int c = 0; c < array2.length; c++) {
                            write(fileWriter, "LINE_DEN_COEFF_" + (c + 1), array2[c], ""+ lineSeparator);
                        }
                        break;
                    case "bSampNum":
                        String[] array3 = value.trim().split(",");
                        for (int c = 0; c < array3.length; c++) {
                            write(fileWriter, "SAMP_NUM_COEFF_" + (c + 1), array3[c], ""+ lineSeparator);
                        }
                        break;
                         case "bSampDen":
                        String[] array4 = value.trim().split(",");
                        for (int c = 0; c < array4.length; c++) {
                            write(fileWriter, "SAMP_DEN_COEFF_" + (c + 1), array4[c], ""+ lineSeparator);
                        }
                        break;
                }
            }
        }
    }
    private static void write(FileWriter fileWriter, String name, String value, String what) throws 
        IOException {
        fileWriter.write(String.format("%s: %s %s\n", name, value, what));
    }
    }`
Answer 2

Как то так:

    import javax.swing.*;
    import java.awt.*;
    public class JFileDialogTest {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() ->
            {
                JFrame frame = new JFrame("_________");
                JTextField textField = new JTextField();
                JButton button = new JButton("Select file");
                button.addActionListener(e -> {
                    JFileChooser fileChooser = new JFileChooser();
                    int res = fileChooser.showOpenDialog(frame);
                    if (res == JFileChooser.APPROVE_OPTION) {
                        textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
                    }
                });
                frame.add(textField, BorderLayout.NORTH);
                frame.add(button, BorderLayout.CENTER);
                frame.pack();
                frame.setSize(300, frame.getHeight());
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setVisible(true);
            });
        }
    }

UPD по вопросу из комментария:
Вам необходимо откорректировать класс так:

    public static class ClassXmlTest implements ActionListener {
        private JTextField f11;
        private JTextField f22;
        public ClassXmlTest(JTextField f11, JTextField f22) {
            this.f11 = f11;
            this.f22 = f22;
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            File xmlFile = new File(f11.getText());
            File txtFile = new File(f22.getText());
            try {
                transform(xmlFile, txtFile);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

тогда действие будете делать так:

    button2.addActionListener(new ClassXmlTest(f1, f2));
READ ALSO
Отсчет секунд на Java

Отсчет секунд на Java

Подскажите, пожалуйста, как реализовать на Java вывод кол-ва секунд, прошедшего со старта программы? Заранее спасибо

180
Область видимости JAVA

Область видимости JAVA

Как перебросить переменную с method1() в method2()?

224
Использование Xerces-2.12

Использование Xerces-2.12

Java 8 из коробки поддерживает xerces-j 27

167
Указание конкретного ip-адреса сокетам в Java.net

Указание конкретного ip-адреса сокетам в Java.net

Требуется создать простейшее клиент-серверное приложениеИспользую библиотеку java

240