Example usage for javax.swing JFileChooser JFileChooser

List of usage examples for javax.swing JFileChooser JFileChooser

Introduction

In this page you can find the example usage for javax.swing JFileChooser JFileChooser.

Prototype

public JFileChooser() 

Source Link

Document

Constructs a JFileChooser pointing to the user's default directory.

Usage

From source file:AST.DesignPatternDetection.java

private void btProgramPathActionPerformed(ActionEvent e) {
    // TODO add your code here
    JFileChooser f2 = new JFileChooser();
    f2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    f2.showDialog(null, null);/*w w w  .  j  av a  2 s  .co  m*/
    tfProgramPath.setText(f2.getSelectedFile().toString());
    //System.out.println(f.getCurrentDirectory());
    //System.out.println(f.getSelectedFile());
}

From source file:hspc.submissionsprogram.AppDisplay.java

AppDisplay() {
    this.setTitle("Dominion High School Programming Contest");
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    this.setResizable(false);

    WindowListener exitListener = new WindowAdapter() {
        @Override/*from ww  w .j av  a 2s.  c  o  m*/
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
    this.addWindowListener(exitListener);

    JTabbedPane pane = new JTabbedPane();
    this.add(pane);

    JPanel submitPanel = new JPanel(null);
    submitPanel.setPreferredSize(new Dimension(500, 500));

    UIManager.put("FileChooser.readOnly", true);
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setBounds(0, 0, 500, 350);
    fileChooser.setVisible(true);
    FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java");
    fileChooser.setFileFilter(javaFilter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setControlButtonsAreShown(false);
    submitPanel.add(fileChooser);

    JSeparator separator1 = new JSeparator();
    separator1.setBounds(12, 350, 476, 2);
    separator1.setForeground(new Color(122, 138, 152));
    submitPanel.add(separator1);

    JLabel problemChooserLabel = new JLabel("Problem:");
    problemChooserLabel.setBounds(12, 360, 74, 25);
    submitPanel.add(problemChooserLabel);

    String[] listOfProblems = Main.Configuration.get("problem_names")
            .split(Main.Configuration.get("name_delimiter"));
    JComboBox problems = new JComboBox<>(listOfProblems);
    problems.setBounds(96, 360, 393, 25);
    submitPanel.add(problems);

    JButton submit = new JButton("Submit");
    submit.setBounds(170, 458, 160, 30);
    submit.addActionListener(e -> {
        try {
            File file = fileChooser.getSelectedFile();
            try {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url"));

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN);
                builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()),
                        ContentType.TEXT_PLAIN);
                builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
                HttpEntity multipart = builder.build();

                uploadFile.setEntity(multipart);

                CloseableHttpResponse response = httpClient.execute(uploadFile);
                HttpEntity responseEntity = response.getEntity();
                String inputLine;
                BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
                try {
                    if ((inputLine = br.readLine()) != null) {
                        int rowIndex = Integer.parseInt(inputLine);
                        new ResultWatcher(rowIndex);
                    }
                    br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (NullPointerException ex) {
            JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        }
    });
    submitPanel.add(submit);

    JPanel clarificationsPanel = new JPanel(null);
    clarificationsPanel.setPreferredSize(new Dimension(500, 500));

    cList = new JList<>();
    cList.setBounds(12, 12, 476, 200);
    cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    cList.setBackground(new Color(254, 254, 255));
    clarificationsPanel.add(cList);

    JButton viewC = new JButton("View");
    viewC.setBounds(12, 224, 232, 25);
    viewC.addActionListener(e -> {
        if (cList.getSelectedIndex() != -1) {
            int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]);
            clarificationDatas.stream().filter(data -> data.getId() == id).forEach(
                    data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse()));
        }
    });
    clarificationsPanel.add(viewC);

    JButton refreshC = new JButton("Refresh");
    refreshC.setBounds(256, 224, 232, 25);
    refreshC.addActionListener(e -> updateCList(true));
    clarificationsPanel.add(refreshC);

    JSeparator separator2 = new JSeparator();
    separator2.setBounds(12, 261, 476, 2);
    separator2.setForeground(new Color(122, 138, 152));
    clarificationsPanel.add(separator2);

    JLabel problemChooserLabelC = new JLabel("Problem:");
    problemChooserLabelC.setBounds(12, 273, 74, 25);
    clarificationsPanel.add(problemChooserLabelC);

    JComboBox problemsC = new JComboBox<>(listOfProblems);
    problemsC.setBounds(96, 273, 393, 25);
    clarificationsPanel.add(problemsC);

    JTextArea textAreaC = new JTextArea();
    textAreaC.setLineWrap(true);
    textAreaC.setWrapStyleWord(true);
    textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    textAreaC.setBackground(new Color(254, 254, 255));

    JScrollPane areaScrollPane = new JScrollPane(textAreaC);
    areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setBounds(12, 312, 477, 134);
    clarificationsPanel.add(areaScrollPane);

    JButton submitC = new JButton("Submit Clarification");
    submitC.setBounds(170, 458, 160, 30);
    submitC.addActionListener(e -> {
        if (textAreaC.getText().length() > 2048) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        } else if (textAreaC.getText().length() < 20) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.",
                    "Error", JOptionPane.WARNING_MESSAGE);
        } else {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                Class.forName(JDBC_DRIVER);

                conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"),
                        Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass"));

                String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)";
                stmt = conn.prepareStatement(sql);

                stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID)));
                stmt.setString(2, String.valueOf(problemsC.getSelectedItem()));
                stmt.setString(3, String.valueOf(textAreaC.getText()));

                textAreaC.setText("");

                stmt.executeUpdate();

                stmt.close();
                conn.close();

                updateCList(false);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
            }
        }
    });
    clarificationsPanel.add(submitC);

    pane.addTab("Submit", submitPanel);
    pane.addTab("Clarifications", clarificationsPanel);

    Timer timer = new Timer();
    TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            updateCList(false);
        }
    };
    timer.schedule(updateTask, 10000, 10000);

    updateCList(false);

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

From source file:com.smanempat.controller.ControllerClassification.java

public void chooseFile(ActionEvent evt, JTextField txtFileDirectory, JTextField txtNumberOfK,
        JLabel labelJumlahData, JButton buttonProses, JTable tablePreview) {
    try {/*from   www . j av  a2s  .  c  o  m*/
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Excel File", "xls",
                "xlsx");
        fileChooser.setFileFilter(fileNameExtensionFilter);

        if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
            txtFileDirectory.setText(fileChooser.getSelectedFile().getAbsolutePath());
            System.out.println("Good, File Chooser runing well!");
            if (txtFileDirectory.getText().endsWith(".xls") || txtFileDirectory.getText().endsWith(".xlsx")) {
                showOnTable(evt, txtFileDirectory, tablePreview);
                labelJumlahData.setText(tablePreview.getRowCount() + " Data");
                txtNumberOfK.setEnabled(true);
                txtNumberOfK.requestFocus();
                buttonProses.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(null,
                        "File dataset harus file spreadsheet dengan ekstensi *xls atau *.xlsx!", "Error",
                        JOptionPane.INFORMATION_MESSAGE, new ImageIcon("src/com/smanempat/image/fail.png"));
                txtFileDirectory.setText("");
                chooseFile(evt, txtFileDirectory, txtNumberOfK, labelJumlahData, buttonProses, tablePreview);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:MessageDigestTest.java

public void loadFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    int r = chooser.showOpenDialog(this);
    if (r == JFileChooser.APPROVE_OPTION) {
        String name = chooser.getSelectedFile().getAbsolutePath();
        computeDigest(loadBytes(name));//  w ww.  ja va2s.  c o m
    }
}

From source file:com.genericworkflownodes.knime.nodes.io.OutputFileNodeDialog.java

/**
 * New pane for configuring MimeFileExporter node dialog.
 *///from  w w w. j a v a2s.  c o m
public OutputFileNodeDialog(final String settingsName) {
    this.settingsName = settingsName;
    dialogPanel = new JPanel();
    componentContainer = new JPanel();
    textField = new JTextField();
    textField.setPreferredSize(new Dimension(300, textField.getPreferredSize().height));
    searchButton = new JButton("Browse");
    searchButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser jfc = new JFileChooser();
            if (!"".equals(textField.getText().trim())
                    && new File(textField.getText().trim()).getParent() != null) {
                jfc.setCurrentDirectory(new File(textField.getText().trim()).getParentFile());
            }

            jfc.setAcceptAllFileFilterUsed(false);
            jfc.setFileFilter(extensionFilter);

            // int returnVal = jfc.showSaveDialog(dialogPanel);
            jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnVal = jfc.showDialog(dialogPanel, "Select output file");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                // validate extension
                if (!extensionFilter.accept(jfc.getSelectedFile())) {
                    String message = "The selected output file has an invalid file extension.\n";
                    if (extensionFilter.getExtensions().length == 1) {
                        message += "Please choose a file with extension: " + extensionFilter.getExtensions()[0];
                    } else {
                        message += "Please choose a file with on of the following extensions: ";
                        message += StringUtils.join(extensionFilter.getExtensions(), ", ");
                    }
                    JOptionPane.showMessageDialog(getPanel(), message, "Selected Output File is invalid.",
                            JOptionPane.WARNING_MESSAGE);
                }
                textField.setText(jfc.getSelectedFile().getAbsolutePath());
            }
        }
    });
    setLayout();
    addComponents();

    addTab("Choose File", dialogPanel);
}

From source file:GuardarImagen.AyudaParaImagen.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    JFileChooser selector = new JFileChooser();
    selector.showOpenDialog(this);
    File file = selector.getSelectedFile();
    try {//from  w  w w . j av a 2  s.co  m
        FileInputStream fis = new FileInputStream(file);
        byte[] datosImagen = IOUtils.toByteArray(fis);
        Galeria g1 = new Galeria();
        g1.setDatosImagen(datosImagen);
        g1.setDescripcion("Porno 1");
        g1.setTitulo("Madonna");
        PersistenciaGaleria p = new PersistenciaGaleria();
        p.guardar(g1);
    } catch (Exception e) {
    }
}

From source file:Result3.java

public void createImageJPG() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("Documents"));
    int retrival = chooser.showSaveDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try {/* ww w. ja  v  a  2 s.  c om*/
            ImageIO.write(bImage1, "jpg", new File(chooser.getSelectedFile() + ".jpg"));
        } catch (IOException ex) {
            Logger.getLogger(Result1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:kindleclippings.quizlet.QuizletSync.java

private static Map<String, List<Clipping>> readClippingsFile() throws IOException {
    // try to find it
    File cl = new File("/Volumes/Kindle/documents/My Clippings.txt");
    if (!cl.canRead()) {
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileNameExtensionFilter("Kindle Clippings", "txt"));
        int result = fc.showOpenDialog(null);
        if (result != JFileChooser.APPROVE_OPTION) {
            return null;
        }/* www.ja v  a  2  s  .  c o  m*/
        cl = fc.getSelectedFile();
    }
    Reader f = new InputStreamReader(new FileInputStream(cl), "UTF-8");
    try {
        MyClippingsReader r = new MyClippingsReader(f);

        Map<String, List<Clipping>> books = new TreeMap<String, List<Clipping>>();

        Clipping l;
        while ((l = r.readClipping()) != null) {
            if (l.getType() != ClippingType.highlight && l.getType() != ClippingType.note) {
                System.err.println("ignored " + l.getType() + " [" + l.getBook() + "]");
                continue;
            }
            String lct = l.getContent().trim();
            if (lct.length() == 0) {
                System.err.println("ignored empty " + l.getType() + " [" + l.getBook() + "]");
                continue;
            }
            if (lct.length() < 10 || !lct.contains(" ")) {
                System.err.println(
                        "ignored too short " + l.getType() + " " + l.getContent() + " [" + l.getBook() + "]");
                continue;
            }
            List<Clipping> clippings = books.get(l.getBook());
            if (clippings == null) {
                clippings = new ArrayList<Clipping>();
                books.put(l.getBook(), clippings);
            }
            clippings.add(l);
        }
        return books;
    } finally {
        f.close();
    }
}

From source file:br.usp.poli.lta.cereda.wsn2spa.Editor.java

public Editor() {
    super("WSN2SPA");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setResizable(false);/*from  ww w .  j  av a 2 s  .  c  o  m*/
    setLayout(new MigLayout());

    txtDotOutput = new JTextField(15);
    txtYamlOutput = new JTextField(15);
    txtFile = new JTextField(10);
    txtFile.setEditable(false);

    checkDFAConvert = new JCheckBox("Convert submachines to DFA's");
    checkMinimize = new JCheckBox("Apply state minimization");
    checkMinimize.setEnabled(false);
    btnOpen = new JButton(
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/wsn2spa/images/open.png")));
    btnRun = new JButton("Convert WSN to SPA",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/wsn2spa/images/play.png")));

    chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files", "txt", "text");
    chooser.setFileFilter(filter);

    btnOpen.addActionListener((ActionEvent ae) -> {
        int value = chooser.showOpenDialog(Editor.this);
        if (value == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
            txtFile.setText(file.getName());
        }
    });

    checkDFAConvert.addChangeListener((ChangeEvent ce) -> {
        checkMinimize.setEnabled(checkDFAConvert.isSelected());
        if (!checkDFAConvert.isSelected()) {
            checkMinimize.setSelected(false);
        }
    });

    btnRun.addActionListener((ActionEvent ae) -> {
        boolean restore = checkMinimize.isEnabled();
        state(false, txtDotOutput, txtYamlOutput, btnOpen, btnRun, checkDFAConvert, checkMinimize);
        try {
            if (!filled(txtDotOutput, txtYamlOutput, txtFile)) {
                throw new Exception(
                        "The fields could not be empty. Make " + "sure to select the grammar file and provide "
                                + "both DOT and YAML patterns in their respective " + "fields.");
            }
            if (!valid(txtDotOutput, txtYamlOutput)) {
                throw new Exception(
                        "The DOT and YAML fields lack the " + "replacement pattern '%s' in order to generate "
                                + "files corresponding to each submachine in the "
                                + "automaton model. Make sure to include the " + "pattern.");
            }
            if (!file.exists()) {
                throw new Exception("The provided grammar file '" + "' does"
                        + " not exist. Make sure the location is correct and" + " try again.");
            }

            String text = FileUtils.readFileToString(file, "UTF-8").trim();
            WirthLexer wl = new WirthLexer(text);
            Generator g = new Generator(wl);
            g.generateAutomaton();

            Writer writer = new Writer(g.getTransitions());
            Map<String, String> map = writer.generateYAMLMap(txtYamlOutput.getText().trim());

            if (Utils.neither(checkDFAConvert, checkMinimize)) {
                br.usp.poli.lta.cereda.wirth2ape.dot.Dot dot = new br.usp.poli.lta.cereda.wirth2ape.dot.Dot(
                        g.getTransitions());
                dot.generate(txtDotOutput.getText().trim());
                for (String key : map.keySet()) {
                    FileUtils.write(new File(key), map.get(key), "UTF-8");
                }
            } else {
                for (String key : map.keySet()) {
                    Triple<Integer, Set<Integer>, List<SimpleTransition>> spec = Reader.read(map.get(key));
                    br.usp.poli.lta.cereda.nfa2dfa.dot.Dot dot = new br.usp.poli.lta.cereda.nfa2dfa.dot.Dot();
                    dot.append(Reader.getName(), "original", spec);

                    Conversion c;

                    if (checkDFAConvert.isSelected()) {
                        c = new Conversion(spec.getThird(), spec.getFirst(), spec.getSecond());
                        spec = c.convert();
                        dot.append(Reader.getName().concat("'"), "converted", spec);
                    }

                    if (checkMinimize.isSelected()) {
                        c = new Conversion(spec.getThird(), spec.getFirst(), spec.getSecond());
                        spec = c.minimize();
                        dot.append(Reader.getName().concat("''"), "minimized", spec);
                    }

                    Yaml yaml = new Yaml();
                    Spec result = Utils.toFormat(spec);
                    result.setName(Reader.getName());
                    map.put(key, yaml.dump(result));

                    String dotname = String.format(txtDotOutput.getText().trim(), Reader.getName());
                    dot.dump(dotname);

                }

                for (String key : map.keySet()) {
                    FileUtils.write(new File(key), map.get(key), "UTF-8");
                }
            }

            showMessage("Success!", "The structured pushdown automaton "
                    + "spec was successfully generated from the provided " + "grammar file.");

        } catch (Exception exception) {
            showException("An exception was thrown", exception);
        }
        state(true, txtDotOutput, txtYamlOutput, btnOpen, btnRun, checkDFAConvert, checkMinimize);
        checkMinimize.setEnabled(restore);
    });

    add(new JLabel("Grammar file:"));
    add(txtFile);
    add(btnOpen, "growx, wrap");
    add(new JLabel("DOT pattern:"));
    add(txtDotOutput, "growx, span 2, wrap");
    add(new JLabel("YAML pattern:"));
    add(txtYamlOutput, "growx, span 2, wrap");
    add(checkDFAConvert, "span 3, wrap");
    add(checkMinimize, "span 3, wrap");
    add(btnRun, "growx, span 3");

    pack();
    setLocationRelativeTo(null);

}

From source file:presenter.MainPresenter.java

@Override
public void saveEmissionsequenceToFile(ActionEvent e) {
    JFileChooser fc = new JFileChooser();

    if (fc.showSaveDialog((Component) e.getSource()) == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {//w  w  w . j a  va2s.  c o  m
            FileWriter fw = new FileWriter(file);
            fw.write(this.emissionsequenceModel.toString());
            fw.flush();
            fw.close();
            this.displayStatus("File was written successfully!");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}