// 保存图像到文件 public void saveImage() throws IOException { JFileChooser jfc = new JFileChooser(); jfc.setDialogTitle("保存"); // 文件过滤器,用户过滤可选择文件 FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg"); jfc.setFileFilter(filter); // 初始化一个默认文件(此文件会生成到桌面上) SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss"); String fileName = sdf.format(new Date()); File filePath = FileSystemView.getFileSystemView().getHomeDirectory(); File defaultFile = new File(filePath + File.separator + fileName + ".jpg"); jfc.setSelectedFile(defaultFile); int flag = jfc.showSaveDialog(this); if (flag == JFileChooser.APPROVE_OPTION) { File file = jfc.getSelectedFile(); String path = file.getPath(); // 检查文件后缀,放置用户忘记输入后缀或者输入不正确的后缀 if (!(path.endsWith(".jpg") || path.endsWith(".JPG"))) { path += ".jpg"; } // 写入文件 ImageIO.write(saveImage, "jpg", new File(path)); System.exit(0); } }
private void loadTopicsFromFile() throws IOException { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("ExtempFiller2"); chooser.setFileFilter( new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt"); } @Override public String getDescription() { return "Text Files"; } }); int response = chooser.showOpenDialog(this); if (response == JFileChooser.APPROVE_OPTION) { // get everything currently researched java.util.List<String> researched = managerPanel.getTopics(); // load everything from file File file = chooser.getSelectedFile(); Scanner readScanner = new Scanner(file); while (readScanner.hasNext()) { String topic = readScanner.nextLine(); if (!researched.contains(topic)) { Topic t = new Topic(topic); managerPanel.addTopic(t); inQueue.add(new InMessage(InMessage.Type.RESEARCH, t)); } } } }
private void saveSrc() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(asmFilter); fileChooser.setFileFilter(asmFilter); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { try { File file = fileChooser.getSelectedFile(); if (fileChooser.getFileFilter() == asmFilter && !asmFilter.accept(file)) { file = new File(file.getAbsolutePath() + asmFilter.getExtensions()[0]); } if (file.exists()) { if (JOptionPane.showConfirmDialog( frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } } PrintStream output = new PrintStream(file); output.print(sourceTextarea.getText()); output.close(); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
void onOpenFileClicked() { if (!maybeSave()) { return; } try { JFileChooser fc = new JFileChooser(); FileNameExtensionFilter filter1 = new FileNameExtensionFilter(strings.getString("filetype." + EXTENSION), EXTENSION); fc.setFileFilter(filter1); int rv = fc.showOpenDialog(this); if (rv == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); Tournament t = new Tournament(); t.loadFile(file); setTournament(file, t); } } catch (Exception e) { JOptionPane.showMessageDialog( this, e, strings.getString("main.error_caption"), JOptionPane.ERROR_MESSAGE); } }
private void saveBin() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(binFilter); fileChooser.setFileFilter(binFilter); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { try { File file = fileChooser.getSelectedFile(); if (fileChooser.getFileFilter() == binFilter && !binFilter.accept(file)) { file = new File(file.getAbsolutePath() + binFilter.getExtensions()[0]); } if (file.exists()) { if (JOptionPane.showConfirmDialog( frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } } FileOutputStream output = new FileOutputStream(file); for (char i : binary) { output.write(i & 0xff); output.write((i >> 8) & 0xff); } output.close(); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
/** * Constructs a new TranslatorComponent with the given filters of the source and destination * files. */ public TranslatorComponent(FileFilter sourceFilter, FileFilter destFilter) { this.sourceFilter = sourceFilter; this.destFilter = destFilter; init(); jbInit(); source.setName("Source"); destination.setName("Destination"); sourceFileChooser = new JFileChooser(); sourceFileChooser.setFileFilter(sourceFilter); destFileChooser = new JFileChooser(); destFileChooser.setFileFilter(destFilter); source.enableUserInput(); destination.disableUserInput(); }
@Override public void mouseClicked(MouseEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); TypeFileFilter fileFilter = new TypeFileFilter("db"); fileChooser.setFileFilter(fileFilter); int result = fileChooser.showOpenDialog(_parent); }
private void createUI() { ShowMaxAction showMaxAction = new ShowMaxAction(); showMaxCheckBox = new JCheckBox(showMaxAction); showMaxCheckBox.setOpaque(false); showMaxCheckBox.setSelected(true); saveFileChooser = new JFileChooser(); saveFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); FileFilter pngFileFilter = new PngFileFilter(); saveFileChooser.setFileFilter(pngFileFilter); graphImageFactories = new GraphImageProducer[] { new TwentyMinutesProducer(mainFrame), new TwoHoursProducer(mainFrame), new TenHoursProducer(mainFrame), new OneDayProducer(mainFrame), new SevenDaysProducer(mainFrame), new ThirtyDaysProducer(mainFrame), new NinetyDaysProducer(mainFrame), new OneYearProducer(mainFrame), }; JPanel graphPanel = new JPanel(new GridLayout(1, 1)); graphLabel = new JLabel(); graphPanel.add(graphLabel); setLayout(new BorderLayout()); add(graphPanel, BorderLayout.CENTER); timerangeComboBox = new JComboBox( new Object[] { "20 minutes", "2 hours", "10 hours", "1 day", "7 days", "30 days", "90 days", "1 year", }); timerangeComboBox.addActionListener(new TimerangeActionListener()); sourcesComboBox = new JComboBox(); sourcesComboBox.addActionListener(new SourcesActionListener()); JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); toolbar.add(new JLabel("Source: ")); toolbar.add(sourcesComboBox); toolbar.addSeparator(); toolbar.add(new JLabel("Timerange: ")); toolbar.add(timerangeComboBox); toolbar.add(showMaxCheckBox); toolbar.addSeparator(); toolbar.add(new JButton(new SaveAction())); add(toolbar, BorderLayout.NORTH); setSelectedGraph(0); }
private File openFile(String title) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Images (*.jpg, *.png, *.gif)", "jpg", "png", "gif"); chooser.setFileFilter(filter); chooser.setCurrentDirectory(openPath); int ret = chooser.showDialog(this, title); if (ret == JFileChooser.APPROVE_OPTION) return chooser.getSelectedFile(); return null; }
private void resetGlobFilter() { if (actualFileFilter != null) { JFileChooser chooser = getFileChooser(); FileFilter currentFilter = chooser.getFileFilter(); if (currentFilter != null && currentFilter.equals(globFilter)) { chooser.setFileFilter(actualFileFilter); chooser.removeChoosableFileFilter(globFilter); } actualFileFilter = null; } }
/* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(final ActionEvent e) { final JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new PKCS12FileFilter()); final int result = chooser.showOpenDialog(getCore()); if (result == JFileChooser.APPROVE_OPTION) { getModel().setPkcs12File(chooser.getSelectedFile()); } }
/** * Use a JFileChooser in Save mode to select files to open. Use a filter for FileFilter subclass * to select for "*.java" files. If a file is selected, then this file will be used as final * output */ boolean saveFile() { File file = null; JFileChooser fc = new JFileChooser(); // Start in current directory fc.setCurrentDirectory(new File(".")); // Set filter for Java source files. fc.setFileFilter(fJavaFilter); // Set to a default name for save. fc.setSelectedFile(fFile); // Open chooser dialog int result = fc.showSaveDialog(this); if (result == JFileChooser.CANCEL_OPTION) { return true; } else if (result == JFileChooser.APPROVE_OPTION) { fFile = fc.getSelectedFile(); String textFile = fFile.toString(); if (fileNo.equalsIgnoreCase("SAVE")) { UpLoadFile.outputfile.setText(textFile); } else if (fileNo.equalsIgnoreCase("SAVE2")) { UpLoadMAGEMLFile.outputfile1.setText(textFile); } else if (fileNo.equalsIgnoreCase("SAVE3")) { UpLoadMAGEMLFile.outputfile2.setText(textFile); } else if (fileNo.equalsIgnoreCase("SAVEJPAG")) { JPEGFileName = textFile; // System.out.println ("JPG filename OpenFileDir= " +JPEGFileName); File fFile = new File(JPEGFileName); if (fFile.exists()) { int response = JOptionPane.showConfirmDialog( null, "Overwrite existing file " + JPEGFileName + " ??", "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.CANCEL_OPTION) { /* go back to reload the file*/ return false; } } SetUpPlotWindow.saveComponentAsJPEG(SetUpPlotWindow.content, JPEGFileName); } return true; } else { return false; } } // saveFile
/* * This function just finds and loads the file */ private boolean loadFile() { JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Load File"); // Choose only files, not directories fc.setFileSelectionMode(JFileChooser.FILES_ONLY); // Start in current directory fc.setCurrentDirectory(new File(".")); // Set filter for Java source files. fc.setFileFilter(fJavaFilter); // Now open chooser int result = fc.showOpenDialog(this); if (result == JFileChooser.CANCEL_OPTION) { // return true; } else if (result == JFileChooser.APPROVE_OPTION) { fFile = fc.getSelectedFile(); String textFile = fFile.toString(); if (fileNo.equalsIgnoreCase("LOAD1")) { UpLoadFile.filePath1.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD2")) { UpLoadFile.filePath2.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD3")) { VisualizationInput.originalFilePath.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD4")) { VisualizationInput.DWDVecFilePath.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD5")) { VisualizationInput.DWDOutputFilePath.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD6")) { UpLoadMAGEMLFile.filePath1.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD7")) { UpLoadMAGEMLFile.filePath2.setText(textFile); } // Get the absolute path for the file being opened filePath = fFile.getAbsolutePath(); if (filePath == null) { // fTextField.setText (filePath); return false; } } else { return false; } return true; } /*End of loadFile*/
private void openFileChooser() { this.fileNameField.setText(defaultFileNameFieldText); JFileChooser fileChooser = new JFileChooser(EmojiTools.getRootDirectory()); FileNameExtensionFilter filter = new FileNameExtensionFilter("Emoji Font File (*.ttf)", "ttf"); fileChooser.setFileFilter(filter); int returnVal = fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { this.fileNameField.setText(fileChooser.getSelectedFile().getName()); this.fontFile = fileChooser.getSelectedFile(); } updateStartButton(); }
private void fileLocButtonActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_fileLocButtonActionPerformed JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Zip Archive (.zip)", "zip"); fileChooser.setFileFilter(filter); fileChooser.setMultiSelectionEnabled(false); if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { loadVCardFile(fileChooser.getSelectedFile()); } checkCurrentPIN(); } // GEN-LAST:event_fileLocButtonActionPerformed
private void setXMLChooserFileFilter(JFileChooser chooser) { chooser.setFileFilter( new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().endsWith("xml"); } @Override public String getDescription() { return "Herolabs xml output file"; } }); }
public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(toolTip); chooser.setDialogType(dialogType); chooser.setFileSelectionMode(fileSelectionMode); chooser.setSelectedFile(new File(textField.getText())); chooser.setFileFilter(preferredFileFilter); // if the user selects APPROVE then take the text if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { // put the text in the text field String pathString = chooser.getSelectedFile().getAbsolutePath(); textField.setText(pathString); } }
public ScaleMainFrame() { super(new BorderLayout()); nameTF = new JTextField(); JPanel top = new JPanel(new BorderLayout()); top.add(new JLabel("Scale Name:"), BorderLayout.WEST); top.add(nameTF, BorderLayout.CENTER); PlayButton pb = new PlayButton("PLAY"); tempoP = new IntSetPanel(1, 10000, "Tempo"); tempoP.setValue(120); JPanel botL = new JPanel(new BorderLayout()); botL.add(pb, BorderLayout.EAST); botL.add(tempoP, BorderLayout.CENTER); PianoKeyB kb = new PianoKeyB(); kb.setPreferredSize(new Dimension(150, 40)); // JPanel botTop = new JPanel(new GridLayout(1, 2)); JPanel botTop = new JPanel(new FlowLayout()); botTop.add(botL); botTop.add(kb); JButton newB = new JButton("New"); saveB = new JButton("Save"); JButton loadB = new JButton("Load"); newB.addActionListener(this); saveB.addActionListener(this); loadB.addActionListener(this); pb.addActionListener(this); JPanel botBot = new JPanel(new GridLayout(1, 3)); botBot.add(newB); botBot.add(saveB); botBot.add(loadB); JPanel bottom = new JPanel(new BorderLayout()); bottom.add(botTop, BorderLayout.CENTER); bottom.add(botBot, BorderLayout.SOUTH); sp = new ScalePanel(this, kb); add(top, BorderLayout.NORTH); add(sp, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setPreferredSize(new Dimension(500, 300)); fileChooser = new JFileChooser(new File("Features/Scales")); filter = new ScaleFilter(); fileChooser.addChoosableFileFilter(filter); fileChooser.setFileFilter(filter); }
private void openFile() { // opens a single file chooser (can select multiple), does not traverse folders. this.copyList = new ArrayList(); final JFileChooser fc = new JFileChooser(currentPath); fc.setMultiSelectionEnabled(true); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); FileNameExtensionFilter filterhtml = new FileNameExtensionFilter("HTML File (.html)", "html"); fc.addChoosableFileFilter(filterhtml); fc.setFileFilter(filterhtml); int result = fc.showOpenDialog(FrontEnd.this); dir = fc.getCurrentDirectory(); dirImp = dir.toString(); switch (result) { case JFileChooser.APPROVE_OPTION: for (File file1 : fc.getSelectedFiles()) { fileImp = file1.toString(); boolean exists = false; for (int i = 0; i < table.getRowCount(); i++) { dir = fc.getCurrentDirectory(); dirImp = dir.toString(); String copyC = dtm.getValueAt(i, 0).toString(); if (duplC.isSelected()) { if (fileImp.endsWith(copyC)) { exists = true; break; } } } if (!exists) { addRow(); dtm.setValueAt(fileImp.substring(67), curRow, 0); dtm.setValueAt(dirImp.substring(67), curRow, 1); curRow++; if (headC == 1) { if (fileImp.substring(67).endsWith(dirImp.substring(67) + ".html")) { curRow--; dtm.removeRow(curRow); } } } } case JFileChooser.CANCEL_OPTION: break; } }
/** Open a file and load the image. */ public void openFile() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); String[] extensions = ImageIO.getReaderFileSuffixes(); chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions)); int r = chooser.showOpenDialog(this); if (r != JFileChooser.APPROVE_OPTION) return; try { Image img = ImageIO.read(chooser.getSelectedFile()); image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); image.getGraphics().drawImage(img, 0, 0, null); } catch (IOException e) { JOptionPane.showMessageDialog(this, e); } repaint(); }
private void openBin() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(binFilter); fileChooser.setFileFilter(binFilter); if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { try { FileInputStream inbinf = new FileInputStream(fileChooser.getSelectedFile()); int len = inbinf.available(); if (len % 2 == 1) throw new IOException(String.format("Odd file size (0x%x)\n", len)); len /= 2; if (len > 0x10000) throw new IOException(String.format("Too large file (0x%x)\n", len)); binary = new char[len]; for (int i = 0; i < len; i++) { int lo = inbinf.read(); int hi = inbinf.read(); if (lo == -1 || hi == -1) throw new IOException("Unable to read\n"); binary[i] = (char) ((hi << 8) | lo); } asmMap = new AsmMap(); Disassembler dasm = new Disassembler(); dasm.init(binary); // TODO attach asmmap StringBuilder sb = new StringBuilder(); while (dasm.getAddress() < binary.length) { int addr = dasm.getAddress(); sb.append(String.format("%-26s ; [%04x] =", dasm.next(true), addr)); int addr2 = dasm.getAddress(); while (addr < addr2) { char i = binary[addr++]; sb.append( String.format(" %04x '%s'", (int) i, (i >= 0x20 && i < 0x7f) ? (char) i : '.')); } sb.append("\n"); } srcBreakpoints.clear(); sourceRowHeader.breakpointsChanged(); sourceTextarea.setText(sb.toString()); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file: %s" + e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
/* * Load some sound data from through a file chooser * We restrict the allowed file formats to .wav, .au .aif .aiff. * We only check agains the file name. The file may actually be encoded * differently. */ public ArrayList<Integer> load() { JFileChooser fileChooser = new JFileChooser(); File thisFile = new File("."); try { fileChooser = new JFileChooser(thisFile.getCanonicalPath()); } catch (Exception e) { System.out.println("Cannot find current directory."); // Will simply load from default path instead. } fileChooser.setFileFilter( new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { if (f.isDirectory()) { return true; } String name = f.getName(); if (name.endsWith(".au") || name.endsWith(".wav") || name.endsWith(".aiff") || name.endsWith(".aif")) { return true; } return false; } public String getDescription() { return ".au, .wav, .aif"; } }); int returnVal = fileChooser.showOpenDialog(new JFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); myHelper = new Helper(file); myHelper.setViewer(this); data = myHelper.getData(); createMainFrame(); return data; } return null; }
private void openSrc() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(asmFilter); fileChooser.setFileFilter(asmFilter); if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { try { FileInputStream input = new FileInputStream(fileChooser.getSelectedFile()); char[] csources = new char[input.available()]; new InputStreamReader(input).read(csources, 0, csources.length); srcBreakpoints.clear(); sourceRowHeader.breakpointsChanged(); sourceTextarea.setText(new String(csources)); asmMap = new AsmMap(); binary = new char[0]; } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
private void prepareChooser(SipModel sipModel) { File directory = new File(sipModel.getPreferences().get(RECENT_DIR, System.getProperty("user.home"))); chooser.setCurrentDirectory(directory); chooser.setFileFilter( new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && (file.getName().endsWith(".xml") || file.getName().endsWith(".xml.gz") || file.getName().endsWith(".xml.zip") || file.getName().endsWith(".csv")); } @Override public String getDescription() { return "Files ending with .xml, .xml.gz, .xml.zip, or .csv"; } }); chooser.setMultiSelectionEnabled(false); }
// Saves the open project to a new file selected by the user public boolean saveFileAs() { // Filter the file chooser by Cue Masher files JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new CueFileFilter()); // Display the existing file location by default if it exists String filePath = soundManager.getProjectFilePath(); if (filePath != null) { File openProjectFile = new File(filePath); fileChooser.setSelectedFile(openProjectFile); } int choice = fileChooser.showSaveDialog(CueMasherPanel.this); if (choice == JFileChooser.APPROVE_OPTION) { // Get the name of the file the user selected File file = fileChooser.getSelectedFile(); filePath = file.getAbsolutePath().trim(); // Make sure that it has a Cue Masher file extension String cueMasherExt = CueFileFilter.CUE_MASHER_FILE_EXT; boolean addExt = false; if (filePath.length() < cueMasherExt.length()) addExt = true; else { String ext = filePath.substring(filePath.length() - cueMasherExt.length(), filePath.length()); if (!ext.equalsIgnoreCase(cueMasherExt)) addExt = true; } // Add the cue masher file extension if it doesn't exist if (addExt) filePath = filePath + cueMasherExt; // Save the project to the selected file soundManager.setProjectFilePath(filePath); return soundManager.saveFile(); } return false; }
/** @return true if file was saved, false if user canceled */ boolean onSaveAsFileClicked() { try { JFileChooser fc = new JFileChooser(); FileNameExtensionFilter filter1 = new FileNameExtensionFilter(strings.getString("filetype." + EXTENSION), EXTENSION); fc.setFileFilter(filter1); int rv = fc.showSaveDialog(this); if (rv == JFileChooser.APPROVE_OPTION) { currentFile = fc.getSelectedFile(); if (!currentFile.getName().endsWith("." + EXTENSION)) { currentFile = new File(currentFile.getPath() + "." + EXTENSION); } doSave(currentFile); refresh(); return true; } } catch (Exception e) { JOptionPane.showMessageDialog( this, e, strings.getString("main.error_caption"), JOptionPane.ERROR_MESSAGE); } return false; }
public static File startFileChooser(Component component, File selectedFile) { // Create a file chooser final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileHidingEnabled(true); fc.setAcceptAllFileFilterUsed(false); if (selectedFile != null) fc.setSelectedFile(selectedFile); fc.setFileFilter( new FileFilter() { @Override public boolean accept(final File file) { if (file.isDirectory()) return true; String ext = Utils.getExtension(file); if (ext != null && ext.equals(Utils.XLS)) { return true; } return false; } @Override public String getDescription() { return "Excel *.xls"; } }); // In response to a button click: final int returnVal = fc.showOpenDialog(component); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // This is where a real application would open the file. Log.d("Opening: " + file.getName() + "."); return file; } else { Log.d("Open command cancelled by user."); } return null; }
/** Sets up dialog for saving instances in a file */ public void setUpFile() { removeAll(); m_fileChooser.setFileFilter( new FileFilter() { public boolean accept(File f) { return f.isDirectory(); } public String getDescription() { return "Directory"; } }); m_fileChooser.setAcceptAllFileFilterUsed(false); try { if (!(((m_dsSaver.getSaver()).retrieveDir()).equals(""))) { String dirStr = m_dsSaver.getSaver().retrieveDir(); if (Environment.containsEnvVariables(dirStr)) { try { dirStr = m_env.substitute(dirStr); } catch (Exception ex) { // ignore } } File tmp = new File(dirStr); tmp = new File(tmp.getAbsolutePath()); m_fileChooser.setCurrentDirectory(tmp); } } catch (Exception ex) { System.out.println(ex); } JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BorderLayout()); JPanel alignedP = new JPanel(); GridBagLayout gbLayout = new GridBagLayout(); alignedP.setLayout(gbLayout); JLabel prefixLab = new JLabel("Prefix for file name", SwingConstants.RIGHT); prefixLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbLayout.setConstraints(prefixLab, gbConstraints); alignedP.add(prefixLab); m_prefixText = new EnvironmentField(); m_prefixText.setEnvironment(m_env); m_prefixText.setToolTipText( "Prefix for file name " + "(or filename itself if relation name is not used)"); /* int width = m_prefixText.getPreferredSize().width; int height = m_prefixText.getPreferredSize().height; m_prefixText.setMinimumSize(new Dimension(width * 2, height)); m_prefixText.setPreferredSize(new Dimension(width * 2, height)); */ gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 1; gbLayout.setConstraints(m_prefixText, gbConstraints); alignedP.add(m_prefixText); try { // m_prefixText = new JTextField(m_dsSaver.getSaver().filePrefix(),25); m_prefixText.setText(m_dsSaver.getSaver().filePrefix()); /* final JLabel prefixLab = new JLabel(" Prefix for file name:", SwingConstants.LEFT); */ JLabel relationLab = new JLabel("Relation name for filename", SwingConstants.RIGHT); relationLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 0; gbLayout.setConstraints(relationLab, gbConstraints); alignedP.add(relationLab); m_relationNameForFilename = new JCheckBox(); m_relationNameForFilename.setSelected(m_dsSaver.getRelationNameForFilename()); m_relationNameForFilename.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_relationNameForFilename.isSelected()) { m_prefixText.setLabel("Prefix for file name"); m_fileChooser.setApproveButtonText("Select directory and prefix"); } else { m_prefixText.setLabel("File name"); m_fileChooser.setApproveButtonText("Select directory and filename"); } } }); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 1; gbConstraints.weightx = 5; gbLayout.setConstraints(m_relationNameForFilename, gbConstraints); alignedP.add(m_relationNameForFilename); } catch (Exception ex) { } // innerPanel.add(m_SaverEditor, BorderLayout.SOUTH); JPanel about = m_SaverEditor.getAboutPanel(); if (about != null) { innerPanel.add(about, BorderLayout.NORTH); } add(innerPanel, BorderLayout.NORTH); // add(m_fileChooser, BorderLayout.CENTER); JLabel directoryLab = new JLabel("Directory", SwingConstants.RIGHT); directoryLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 0; gbLayout.setConstraints(directoryLab, gbConstraints); alignedP.add(directoryLab); m_directoryText = new EnvironmentField(); // m_directoryText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_directoryText.setEnvironment(m_env); /* width = m_directoryText.getPreferredSize().width; height = m_directoryText.getPreferredSize().height; m_directoryText.setMinimumSize(new Dimension(width * 2, height)); m_directoryText.setPreferredSize(new Dimension(width * 2, height)); */ try { m_directoryText.setText(m_dsSaver.getSaver().retrieveDir()); } catch (IOException ex) { // ignore } JButton browseBut = new JButton("Browse..."); browseBut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { final JFrame jf = new JFrame("Choose directory"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_fileChooser, BorderLayout.CENTER); jf.pack(); jf.setVisible(true); m_fileChooserFrame = jf; } catch (Exception ex) { ex.printStackTrace(); } } }); JPanel efHolder = new JPanel(); efHolder.setLayout(new BorderLayout()); JPanel bP = new JPanel(); bP.setLayout(new BorderLayout()); bP.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); bP.add(browseBut, BorderLayout.CENTER); efHolder.add(m_directoryText, BorderLayout.CENTER); efHolder.add(bP, BorderLayout.EAST); // efHolder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 1; gbLayout.setConstraints(efHolder, gbConstraints); alignedP.add(efHolder); JLabel relativeLab = new JLabel("Use relative file paths", SwingConstants.RIGHT); relativeLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 0; gbLayout.setConstraints(relativeLab, gbConstraints); alignedP.add(relativeLab); m_relativeFilePath = new JCheckBox(); m_relativeFilePath.setSelected( ((FileSourcedConverter) m_dsSaver.getSaver()).getUseRelativePath()); m_relativeFilePath.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ((FileSourcedConverter) m_dsSaver.getSaver()) .setUseRelativePath(m_relativeFilePath.isSelected()); } }); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 1; gbLayout.setConstraints(m_relativeFilePath, gbConstraints); alignedP.add(m_relativeFilePath); JButton OKBut = new JButton("OK"); OKBut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { (m_dsSaver.getSaver()).setFilePrefix(m_prefixText.getText()); (m_dsSaver.getSaver()).setDir(m_directoryText.getText()); m_dsSaver.setRelationNameForFilename(m_relationNameForFilename.isSelected()); } catch (Exception ex) { ex.printStackTrace(); } m_parentFrame.dispose(); } }); JButton CancelBut = new JButton("Cancel"); CancelBut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { m_parentFrame.dispose(); } }); JPanel butHolder = new JPanel(); butHolder.setLayout(new FlowLayout()); butHolder.add(OKBut); butHolder.add(CancelBut); JPanel holder2 = new JPanel(); holder2.setLayout(new BorderLayout()); holder2.add(alignedP, BorderLayout.NORTH); holder2.add(butHolder, BorderLayout.SOUTH); add(holder2, BorderLayout.SOUTH); }
@SuppressWarnings({"unchecked", "serial"}) public SourcesSelector(final ProcessLog logger) { super(new BorderLayout(0, 5)); this.logger = logger; JPanel buttons = new JPanel(new GridLayout(5, 1, 0, 10)); buttons.add( new JButton( new AbstractAction("Add Source") { @Override public void actionPerformed(ActionEvent e) { chooser.showOpenDialog(null); } })); buttons.add( new JButton( new AbstractAction("Load Sources") { @Override public void actionPerformed(ActionEvent e) { // TODO: use an xml config file to load sources from a saved file refreshModules(); } })); buttons.add( new JButton( new AbstractAction("Remove Source") { @Override public void actionPerformed(ActionEvent e) { int[] selected = list.getSelectedIndices(); int pos = selected.length; while (pos > 0) dir.remove(selected[--pos]); refreshModules(); } })); buttons.add( new JButton( new AbstractAction("Remove All Sources") { @Override public void actionPerformed(ActionEvent e) { dir.removeAllElements(); refreshModules(); } })); buttons.add( new JButton( new AbstractAction("Clear Log") { @Override public void actionPerformed(ActionEvent e) { logger.clear(); } })); splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitter.setLeftComponent(buttons); dir = new DefaultListModel(); chooser = new JFileChooser(); chooser.setFileFilter( new FileFilter() { @Override public String getDescription() { return "Directories Or Jars"; } @Override public boolean accept(File f) { return f.isDirectory() || f.toString().endsWith(".jar"); } }); chooser.setMultiSelectionEnabled(true); chooser.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (File f : chooser.getSelectedFiles()) { int ind = dir.indexOf(f); if (ind > -1) dir.remove(ind); dir.add(0, f); } refreshModules(); } }); list = new JList(dir); list.setCellRenderer( new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { try { File f = (File) value; if (f.isDirectory()) { return super.getListCellRendererComponent( list, f.toString(), index, isSelected, cellHasFocus); } else { return super.getListCellRendererComponent( list, f.getName(), index, isSelected, cellHasFocus); } } catch (Exception e) { e.printStackTrace(); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } }); list.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { int[] selected = list.getSelectedIndices(); if (selected.length > 0) { File f = (File) dir.get(selected[0]); if (f.isDirectory()) { chooser.setCurrentDirectory(f); } else { chooser.setCurrentDirectory(f.getParentFile()); } } } }); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); JScrollPane scroller = new JScrollPane( list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); splitter.setRightComponent(scroller); add(splitter); splitter.setDividerLocation(0.5); }
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == open) { if (isInProgress()) { systemIsBusy(); return; } checkRunned(); chooser = new JFileChooser(); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileFilter(new InputFileFilter(false)); if (loadedFile != null) chooser.setSelectedFile(loadedFile); int returnValue = chooser.showOpenDialog(this); if (returnValue == JFileChooser.APPROVE_OPTION) { boolean approved = ((InputFileFilter) chooser.getFileFilter()).isFileApproved(chooser.getSelectedFile()); if (approved) { startProgress(); new MultiThread( new Runnable() { public void run() { try { loadedFile = chooser.getSelectedFile(); FileInputStream fis = new FileInputStream(loadedFile); InputParser ip = new InputParser(fis); if (ip.parseInput()) { field = new Field(new ArrayList<Point>(Arrays.asList(ip.getPoints()))); minAlgo.setText(String.valueOf(ip.minimumClusters)); maxAlgo.setText(String.valueOf(ip.maximumClusters)); } } catch (FileNotFoundException e1) { } contentpanel.center(); stopProgress(); } }) .start(); } } } else if (e.getSource() == center) { if (isInProgress()) { systemIsBusy(); return; } startProgress(); new MultiThread( new Runnable() { public void run() { contentpanel.removeMouseWheelListener(contentpanel); contentpanel.center(); contentpanel.addMouseWheelListener(contentpanel); stopProgressRepaint(); } }) .start(); } else if (e.getSource() == save) { if (isInProgress()) { systemIsBusy(); return; } checkRunned(); chooser = new JFileChooser(); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileFilter(new InputFileFilter(true)); if (loadedFile != null) chooser.setSelectedFile(loadedFile); int returnValue = chooser.showSaveDialog(this); if (returnValue == JFileChooser.APPROVE_OPTION) { boolean approved = ((InputFileFilter) chooser.getFileFilter()).isFileApproved(chooser.getSelectedFile()); if (approved) { loadedFile = chooser.getSelectedFile(); boolean halt = loadedFile.exists(); if (halt) { int i = JOptionPane.showInternalConfirmDialog( c, "Are you sure you want to override this file?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (i == JOptionPane.YES_OPTION) { halt = false; } } if (!halt) { try { PrintWriter pw = new PrintWriter(new FileWriter(loadedFile)); pw.println("find " + field.getNumberOfClusters() + " clusters"); pw.println(field.size() + " points"); Object[] obj = field.toArray(); for (int i = 0; i < obj.length; i++) { Point p = (Point) obj[i]; pw.println(p.getX() + " " + p.getY()); } pw.close(); } catch (IOException e1) { } } } } } else if (e.getSource() == clear) { if (isInProgress()) { systemIsBusy(); return; } int i = JOptionPane.showInternalConfirmDialog( c, "Are you sure you want to clear the field?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); checkRunned(); if (i == JOptionPane.YES_OPTION) { field = new Field(); updateContentPanel(); } } else if (e.getSource() == circle) { contentpanel.setSelectionMode(ContentPanel.SELECT_CIRCLE); } else if (e.getSource() == square) { contentpanel.setSelectionMode(ContentPanel.SELECT_SQUARE); } else if (e.getSource() == addacluster) { if (isInProgress()) { systemIsBusy(); return; } checkRunned(); contentpanel.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); } else if (e.getSource() == addnoise) { if (isInProgress()) { systemIsBusy(); return; } checkRunned(); final String s = JOptionPane.showInternalInputDialog( c, "How many points?", "Add noise", JOptionPane.QUESTION_MESSAGE); startProgress(); new MultiThread( new Runnable() { public void run() { if (s != null) { int number; try { number = Integer.parseInt(s); } catch (Exception ex) { number = 0; } int tillX = 1000000000; int tillY = 1000000000; int addX = 0; int addY = 0; if (inRectangle.isSelected()) { Rectangle r = field.getBoundingRectangle(); if (!(r.x1 == 0 && r.y1 == 0 && r.x2 == 0 && r.y2 == 0)) { tillX = r.x2 - r.x1; addX = r.x1; tillY = r.y2 - r.y1; addY = r.y1; } else { tillX = 500000000; tillY = 500000000; } } for (int i = 0; i < number; i++) { int x = random.nextInt(tillX); x += addX; int y; boolean busy = true; while (busy) { y = random.nextInt(tillY); y += addY; boolean inside = false; Object[] array = field.toArray(); for (int j = 0; j < field.size(); j++) { if (((Point) array[j]).compareTo(x, y)) { inside = true; break; } } if (!inside) { field.add(new Point(x, y)); busy = false; } } } } stopProgress(); } }) .start(); } else if (e.getSource() == run) { if (isInProgress()) { systemIsBusy(); return; } checkRunned(); startProgress(); runAlgo(); } }