Example usage for javax.swing JFileChooser setVisible

List of usage examples for javax.swing JFileChooser setVisible

Introduction

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

Prototype

@BeanProperty(hidden = true, visualUpdate = true)
public void setVisible(boolean aFlag) 

Source Link

Document

Makes the component visible or invisible.

Usage

From source file:com.novadart.silencedetect.SilenceDetect.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new BasicParser();
    try {/* w w  w .j ava 2 s . com*/
        // parse the command line arguments
        CommandLine line = parser.parse(OPTIONS, args);

        if (line.hasOption("h")) {

            printHelp();

        } else {

            String decibels = "-10";
            if (line.hasOption("b")) {
                decibels = "-" + line.getOptionValue("b");
            } else {
                throw new RuntimeException();
            }

            String videoFile = null;

            if (line.hasOption("i")) {

                videoFile = line.getOptionValue("i");

                Boolean debug = line.hasOption("d");

                if (line.hasOption("t")) {

                    System.out.println(printAudioTracksList(videoFile, debug));

                } else if (line.hasOption("s")) {

                    int trackNumber = Integer.parseInt(line.getOptionValue("s"));
                    System.out.println(printAudioTrackSilenceDuration(videoFile, trackNumber, decibels, debug));

                } else {

                    printHelp();

                }

            } else if (line.hasOption("-j")) {

                // choose file
                final JFileChooser fc = new JFileChooser();
                fc.setVisible(true);
                int returnVal = fc.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    videoFile = fc.getSelectedFile().getAbsolutePath();

                } else {
                    return;
                }

                JTextArea tracks = new JTextArea();
                tracks.setText(printAudioTracksList(videoFile, true));
                JSpinner trackNumber = new JSpinner();
                trackNumber.setValue(1);
                final JComponent[] inputs = new JComponent[] { new JLabel("Audio Tracks"), tracks,
                        new JLabel("Track to analyze"), trackNumber };
                JOptionPane.showMessageDialog(null, inputs, "Select Audio Track", JOptionPane.PLAIN_MESSAGE);

                JTextArea results = new JTextArea();
                results.setText(printAudioTrackSilenceDuration(videoFile, (int) trackNumber.getValue(),
                        decibels, false));
                final JComponent[] resultsInputs = new JComponent[] { new JLabel("Results"), results };
                JOptionPane.showMessageDialog(null, resultsInputs, "RESULTS!", JOptionPane.PLAIN_MESSAGE);

            } else {
                printHelp();
                return;
            }

        }

    } catch (ParseException | IOException | InterruptedException exp) {
        // oops, something went wrong
        System.out.println("There was a problem :(\nReason: " + exp.getMessage());
    }
}

From source file:Main.java

public static void main(String[] argv) {

    JFileChooser chooser = new JFileChooser();

    chooser.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
                JFileChooser chooser = (JFileChooser) evt.getSource();
                File oldFile = (File) evt.getOldValue();
                File newFile = (File) evt.getNewValue();

                System.out.println(oldFile);
                System.out.println(newFile);
                System.out.println(chooser.getSelectedFile());
            } else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
                JFileChooser chooser = (JFileChooser) evt.getSource();
                File[] oldFiles = (File[]) evt.getOldValue();
                File[] newFiles = (File[]) evt.getNewValue();

                Arrays.toString(oldFiles);
                Arrays.toString(newFiles);
                File[] files = chooser.getSelectedFiles();
                Arrays.toString(files);
            }// w w w.j  a va 2s . c  o m
        }
    });

    chooser.setVisible(true);

}

From source file:MainClass.java

public MainClass() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    this.getContentPane().add(fileChooser);
    fileChooser.setVisible(true);
}

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   w w  w  .  j  a v a2 s .  com
        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:org.tros.logo.swing.LogoMenuBar.java

/**
 * Set up the export menu.//from   www . j a  va  2 s  .com
 *
 * @return
 */
private JMenu setupExportMenu() {
    JMenu exportMenu = new JMenu(Localization.getLocalizedString("ExportMenu"));

    JMenuItem exportGif = new JMenuItem(Localization.getLocalizedString("ExportGIF"));
    JMenuItem exportPng = new JMenuItem(Localization.getLocalizedString("ExportPNG"));
    JMenuItem exportSvg = new JMenuItem(Localization.getLocalizedString("ExportSVG"));

    exportSvg.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                if (Drawable.class.isAssignableFrom(canvas.getClass())) {
                    try (FileOutputStream fos = new FileOutputStream(new File(filename))) {
                        generateSVG((Drawable) canvas, fos);
                        fos.flush();
                    } catch (IOException ex) {
                        org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoMenuBar.class).warn(null,
                                ex);
                    }
                }
            }
        }
    });

    exportGif.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                final String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Drawable.class.isAssignableFrom(canvas.getClass())
                                && BufferedImageProvider.class.isAssignableFrom((canvas.getClass()))) {
                            try {
                                generateGIF(((Drawable) canvas).cloneDrawable(), (BufferedImageProvider) canvas,
                                        filename);
                            } catch (SVGGraphics2DIOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                });
                t.setDaemon(true);
                t.start();
            }
        }
    });
    exportPng.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                // retrieve image
                if (BufferedImageProvider.class.isAssignableFrom(canvas.getClass())) {
                    generatePNG((BufferedImageProvider) canvas, filename);
                }
            }
        }
    });

    exportMenu.add(exportSvg);
    exportMenu.add(exportGif);
    exportMenu.add(exportPng);
    exportMenu.setMnemonic('X');
    exportSvg.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.ALT_MASK));
    exportGif.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.ALT_MASK));
    exportPng.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.ALT_MASK));
    return (exportMenu);
}

From source file:org.zaproxy.zap.extension.customFire.CustomFireDialog.java

/**
 * Saves input vectors tab//  w w w . ja va  2 s.  c  o  m
 * @param scannerParam void `
 */
protected void saveScannerParam(ScannerParam scannerParam) {

    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
    File file = new File(Constant.getZapHome(), "Input Vectors.ser");
    chooser.setSelectedFile(file);

    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".ser")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("customFire.custom.file.format.csp.ser");
        }
    });
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        try {

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scannerParam);
            oos.close();
            fos.close();
            View.getSingleton()
                    .showMessageDialog(Constant.messages.getString("customFire.custom.ser.saveIV.success"));

        } catch (IOException e1) {
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("customFire.custom.ser.saveIV.error"));
            return;
        }
    }
    if (rc == JFileChooser.CANCEL_OPTION) {
        chooser.setVisible(false);
        return;
    }
}

From source file:org.zaproxy.zap.extension.customFire.TechnologyTreePanel.java

/**
 * To save tech settings// w  ww .jav  a  2s .c om
 *  void `
 */
public void saveTechState() {

    //Do Tech ser
    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
    File file = new File(Constant.getZapHome(), "Tech.ser");
    chooser.setSelectedFile(file);

    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".ser")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("customFire.custom.file.format.csp.ser");
        }
    });
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        try {

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(TechnologyTreePanel.this);
            oos.close();
            fos.close();
            View.getSingleton()
                    .showMessageDialog(Constant.messages.getString("customFire.custom.ser.saveTech.success"));

        } catch (IOException e1) {
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("customFire.custom.ser.saveTech.error"));
            return;
        }
    }
    if (rc == JFileChooser.CANCEL_OPTION) {
        chooser.setVisible(false);
        return;
    }

}

From source file:ui.FtpDialog.java

private void uploadFileBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadFileBtActionPerformed

    if (connected) {
        JFileChooser uploadFileChooser = new JFileChooser();
        uploadFileChooser.setPreferredSize(new Dimension(650, 450));

        File rootDirectory = new File("C:\\");

        uploadFileChooser//from  ww  w  .  j  a  v a  2  s  .  co  m
                .setCurrentDirectory(uploadFileChooser.getFileSystemView().getParentDirectory(rootDirectory));

        uploadFileChooser.setDialogTitle("File to upload");
        int result = uploadFileChooser.showOpenDialog(this);
        switch (result) {

        case JFileChooser.APPROVE_OPTION:
            selectedFile = uploadFileChooser.getSelectedFile();

            Trace.trc("File to upload: " + selectedFile.getName() + " File size: "
                    + FileUtils.byteCountToDisplaySize(selectedFile.length()));

            if (connected) {
                if (!selectedFile.equals(null)) {
                    try {
                        input = new FileInputStream(selectedFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    pb = new ProgressBar();
                    pb.execute();

                    uploadFileChooser.setVisible(false);

                } else {
                    JOptionPane.showMessageDialog(rootFrame, "No file to upload has been chosen!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(rootFrame, "Not connected to a server, cannot upload file!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
            break;

        case JFileChooser.CANCEL_OPTION:
            Trace.trc("Closing file chooser dialog");
            break;

        case JFileChooser.ERROR_OPTION:
            Trace.trc("An error occured");
            break;
        }

    } else {
        JOptionPane.showMessageDialog(rootFrame, "Not connected to a server, cannot upload file!", "Error",
                JOptionPane.ERROR_MESSAGE);
    }

}