List of usage examples for javax.swing JFileChooser setFileFilter
@BeanProperty(preferred = true, description = "Sets the File Filter used to filter out files of type.") public void setFileFilter(FileFilter filter)
From source file:com.sf.energy.transfer.form.DataConfiguration.java
/** * ??//from w w w .j av a 2s.co m * @param evt ? */ private void scanActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fc = new JFileChooser(); File directory = new File(dir); // ?? fc.setCurrentDirectory(directory); fc.setDialogTitle(""); // FileNameExtensionFilter filter1 = new FileNameExtensionFilter(".xls", "xls"); fc.addChoosableFileFilter(filter1); FileNameExtensionFilter filter2 = new FileNameExtensionFilter(".dmp", "dmp"); fc.addChoosableFileFilter(filter1); // fc.setFileFilter(fc.getAcceptAllFileFilter()); int intRetVal = fc.showOpenDialog(new JFrame()); // ? if (intRetVal == JFileChooser.APPROVE_OPTION) { // ? dir = fc.getSelectedFile().getPath(); // filePath.setText(dir); } }
From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java
/** * Saves the current file under a new name/path * * @throws InterruptedException if there is an error when waiting for the saves to finish *///from w ww . j a v a 2 s. c o m private void saveAs() throws InterruptedException { if (askToSave()) { final JFileChooser fc = new JFileChooser(Main.getFilePath()); fc.setFileFilter(new DrillFileFilter()); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fc.showSaveDialog(this); File file = fc.getSelectedFile(); String name, path; if (returnVal == JFileChooser.APPROVE_OPTION) { try { path = file.getCanonicalPath(); path = path.substring(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1); name = file.getName().toLowerCase().endsWith(".drill") ? file.getName() : file.getName() + ".drill"; Main.setFilePath(path); Main.setPagesFileName(name); Main.savePages().join(); Main.saveState().join(); Main.load(false); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java
/** * Gets the show to open and opens the respective json file. *//* w ww.j av a 2 s . c om*/ private void openShow() { if (askToSave()) { File file; final JFileChooser fc = new JFileChooser(Main.getFilePath()); fc.setFileFilter(new DrillFileFilter()); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal; do { returnVal = fc.showOpenDialog(this); file = fc.getSelectedFile(); } while (returnVal != JFileChooser.CANCEL_OPTION && returnVal != JFileChooser.ERROR_OPTION && !file.exists()); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String name, path; path = file.getCanonicalPath(); path = path.substring(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1); name = file.getName().toLowerCase().endsWith(".drill") ? file.getName() : file.getName() + ".drill"; Main.setFilePath(path); Main.setPagesFileName(name); Main.load(false); desktop.createNewInternalFrames(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java
/** * Creates a new json file for a new show * * @throws InterruptedException if there is an error when waiting for the saves to finish *//*from ww w . ja va 2 s. com*/ private void newShow() throws InterruptedException { if (askToSave()) { final JFileChooser fc = new JFileChooser(new File(Main.getFilePath())); fc.setFileFilter(new DrillFileFilter()); int returnVal = fc.showDialog(this, "New File"); String name, path; if (returnVal == JFileChooser.APPROVE_OPTION) { try { File file = fc.getSelectedFile(); path = file.getCanonicalPath(); path = path.substring(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1); name = file.getName().toLowerCase().endsWith(".drill") ? file.getName() : file.getName() + ".drill"; Main.setFilePath(path); Main.setPagesFileName(name); Main.saveState().join(); Main.load(false); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:jpad.MainEditor.java
public void saveAs() { if (_isOSX || ostype == ostype.Linux || ostype == ostype.Other) { saveAs_OSX_Nix();/*www .j a v a 2 s. c o m*/ saveFile(curFile); } else /* Windows */ { JFileChooser fc = new JFileChooser(); if (curFile != null) fc.setSelectedFile(new File(curFile)); else fc.setSelectedFile(new File("Untitled.txt")); fc.setDialogTitle("Save Text File"); fc.setFileFilter(new FileNameExtensionFilter("Plain Text Files", "txt")); int returnval = fc.showSaveDialog(this); if (returnval == 0) { curFile = fc.getSelectedFile().getAbsolutePath(); if (!curFile.endsWith(".txt")) curFile = curFile + ".txt"; hasChanges = false; hasSavedToFile = true; saveFile(curFile); } } }
From source file:net.sf.mzmine.chartbasics.gui.swing.EChartPanel.java
/** * Opens a file chooser and gives the user an opportunity to save the chart in PNG format. * * @throws IOException if there is an I/O error. *//*from www .java 2 s. co m*/ @Override public void doSaveAs() throws IOException { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs()); FileNameExtensionFilter filter = new FileNameExtensionFilter( localizationResources.getString("PNG_Image_Files"), "png"); fileChooser.addChoosableFileFilter(filter); fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { String filename = fileChooser.getSelectedFile().getPath(); if (isEnforceFileExtensions()) { if (!filename.endsWith(".png")) { filename = filename + ".png"; } } ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(), getChartRenderingInfo()); } }
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 www. j a v a 2 s .c om 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:ch.fork.AdHocRailway.ui.locomotives.configuration.LocomotiveConfig.java
public void chooseLocoImage() { File previousLocoDir = ctx.getPreviousLocoDir(); if (previousLocoDir == null) { previousLocoDir = new File("locoimages"); }/*from ww w .j av a2 s .c o m*/ final JFileChooser chooser = new JFileChooser(previousLocoDir); final ImagePreviewPanel preview = new ImagePreviewPanel(); chooser.setAccessory(preview); chooser.addPropertyChangeListener(preview); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setFileFilter(new FileFilter() { @Override public String getDescription() { return "Image Files"; } @Override public boolean accept(final File f) { if (f.isDirectory()) { return true; } if (StringUtils.endsWithAny(f.getName().toLowerCase(), ".png", ".gif", ".bmp", ".jpg")) { return true; } return false; } }); final int ret = chooser.showOpenDialog(LocomotiveConfig.this); if (ret == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); ctx.setPreviousLocoDir(selectedFile.getParentFile()); presentationModel.getBean().setImage(selectedFile.getName()); final String image = presentationModel.getBean().getImage(); presentationModel.getBean() .setImageBase64(LocomotiveImageHelper.getImageBase64(presentationModel.getBean())); if (image != null && !image.isEmpty()) { imageLabel.setIcon(LocomotiveImageHelper.getLocomotiveIcon(presentationModel.getBean())); pack(); } else { imageLabel.setIcon(null); pack(); } } }
From source file:io.github.jeremgamer.editor.panels.MusicFrame.java
public MusicFrame(JFrame frame, final GeneralSave gs) { ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>(); try {/*from w w w . j a v a 2 s.com*/ icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png"))); } catch (IOException e1) { e1.printStackTrace(); } this.setIconImages((List<? extends Image>) icons); this.setTitle("Musique"); this.setSize(new Dimension(300, 225)); this.addWindowListener(new WindowListener() { @Override public void windowActivated(WindowEvent event) { } @Override public void windowClosed(WindowEvent event) { } @Override public void windowClosing(WindowEvent event) { try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void windowDeactivated(WindowEvent event) { } @Override public void windowDeiconified(WindowEvent event) { } @Override public void windowIconified(WindowEvent event) { } @Override public void windowOpened(WindowEvent event) { } }); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS)); this.setModal(true); this.setLocationRelativeTo(frame); JPanel properties = new JPanel(); properties.setBorder(BorderFactory.createTitledBorder("Lecture")); ButtonGroup bg = new ButtonGroup(); bg.add(one); bg.add(loop); one.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { JRadioButton rb = (JRadioButton) event.getSource(); if (rb.isSelected()) { gs.set("music.reading", 0); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { if (clip.isRunning()) clip.loop(0); } } } }); loop.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { JRadioButton rb = (JRadioButton) event.getSource(); if (rb.isSelected()) { gs.set("music.reading", 1); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { if (clip.isRunning()) clip.loop(Clip.LOOP_CONTINUOUSLY); } } } }); properties.add(one); properties.add(loop); if (gs.getInt("music.reading") == 0) { one.setSelected(true); } else { loop.setSelected(true); } volume.setMaximum(100); volume.setMinimum(0); volume.setValue(30); volume.setPaintTicks(true); volume.setPaintLabels(true); volume.setMinorTickSpacing(10); volume.setMajorTickSpacing(20); volume.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { JSlider slider = (JSlider) event.getSource(); double value = slider.getValue(); gain = value / 100; dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0); if (clip != null) gainControl.setValue(dB); gs.set("music.volume", (int) value); } }); volume.setValue(gs.getInt("music.volume")); properties.add(volume); properties.setPreferredSize(new Dimension(300, 125)); content.add(properties); JPanel browsePanel = new JPanel(); browsePanel.setBorder(BorderFactory.createTitledBorder("")); JButton browse = new JButton("Parcourir..."); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { preview.setEnabled(false); browse.setText(""); try { browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } } browse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton button = (JButton) event.getSource(); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { if (clip != null) { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } name.setText(""); preview.setEnabled(false); button.setText("Parcourir..."); button.setIcon(null); new File("projects/" + Editor.getProjectName() + "/music.wav").delete(); gs.set("music.name", ""); } else { String path = null; JFileChooser chooser = new JFileChooser(Editor.lastPath); FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav"); chooser.setFileFilter(filter); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = chooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { path = chooser.getSelectedFile().getAbsolutePath(); Editor.lastPath = chooser.getSelectedFile().getParent(); copyMusic(new File(path)); button.setText(""); try { button.setIcon( new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } gs.set("music.name", new File(path).getName()); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } name.setText(new File(path).getName()); preview.setEnabled(true); } } } }); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { preview.setEnabled(true); } else { preview.setEnabled(false); } preview.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JToggleButton tb = (JToggleButton) event.getSource(); if (tb.isSelected()) { try { audioStream = AudioSystem.getAudioInputStream( new File("projects/" + Editor.getProjectName() + "/music.wav")); format = audioStream.getFormat(); info = new DataLine.Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); clip.open(audioStream); clip.start(); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(dB); if (loop.isSelected()) { clip.loop(Clip.LOOP_CONTINUOUSLY); } else { clip.loop(0); } clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { Clip clip = (Clip) event.getSource(); if (!clip.isRunning()) { preview.setSelected(false); clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }); } catch (Exception exc) { exc.printStackTrace(); } } else { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }); JPanel buttons = new JPanel(); buttons.setLayout(new BorderLayout()); buttons.add(browse, BorderLayout.WEST); buttons.add(preview, BorderLayout.EAST); browsePanel.setLayout(new BorderLayout()); browsePanel.add(buttons, BorderLayout.NORTH); browsePanel.add(name, BorderLayout.SOUTH); name.setPreferredSize(new Dimension(280, 25)); name.setText(gs.getString("music.name")); content.add(browsePanel); this.setContentPane(content); this.setVisible(true); }
From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileGraphicDetailPanel.java
private Component createExportButton() { exportButton = new JButton(new AbstractAction(null, UIAgent.getInstance().getIcon(UIAgent.ICON_EXPORT_24)) { private static final long serialVersionUID = 9021437098555924654L; @Override//w w w.j a va 2 s.c o m public void actionPerformed(ActionEvent e) { JFileChooser ch = new JFileChooser(); ch.setFileFilter(new ExtensionFilter("xls", "Excel File")); int i = ch.showSaveDialog(null); if (i == JFileChooser.APPROVE_OPTION) { DiveProfileExcelParser p = new DiveProfileExcelParser(); try { File f = ch.getSelectedFile(); if (FileUtilities.getExtension(f) == null || !("xls".equals(FileUtilities.getExtension(f)))) { f = new File(f.getAbsoluteFile() + ".xls"); } p.export(currentDive.getDate(), diveProfile, f); } catch (IOException e1) { ExceptionDialog.showDialog(e1, DiveProfileGraphicDetailPanel.this); LOGGER.error(e1.getMessage()); } } } }); exportButton.setToolTipText("Export"); return exportButton; }