@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); int choose = f.showSaveDialog(getContentPane()); if (choose == JFileChooser.APPROVE_OPTION) { BufferedWriter brw = null; try { File file = f.getSelectedFile(); brw = new BufferedWriter(new FileWriter(file)); int i = td.getSelectedIndex(); TextDocument ta = (TextDocument) td.getComponentAt(i); ta.write(brw); ta.fileName = file.getName(); // 將檔案名稱更新為存檔的名稱 td.setTitleAt(td.getSelectedIndex(), ta.fileName); ta.file = file; ta.save = true; // 設定已儲存 System.out.println("Save as pass!"); td.setTitleAt(i, ta.fileName); // 更新標題名稱 } catch (Exception exc) { exc.printStackTrace(); } finally { try { brw.close(); } catch (Exception ecx) { ecx.printStackTrace(); } } } } else { JOptionPane.showMessageDialog(null, "沒有檔案可以儲存!"); } }
@Override public void actionPerformed(ActionEvent e) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); // 設定檔案選擇器 int choose = f.showOpenDialog(getContentPane()); // 顯示檔案選取 if (choose == JFileChooser.OPEN_DIALOG) { // 有開啟檔案的話,開始讀檔 BufferedReader br = null; try { File file = f.getSelectedFile(); br = new BufferedReader(new FileReader(file)); TextDocument ta = new TextDocument(file.getName(), file); ta.addKeyListener(new SystemTrackSave()); ta.read(br, null); td.add(ta); td.setTitleAt(docCount++, file.getName()); } catch (Exception exc) { exc.printStackTrace(); } finally { try { br.close(); } catch (Exception ecx) { ecx.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); } }
// 保存图像到文件 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); } }
/** * 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(); }
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; } }
/** * 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*/
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); }
/** Effectue differentes actions en fonction du bouton que l'on clique */ @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Réinitialiser")) { this.maGrille.viderTabCases(); } else if (e.getActionCommand().equals("Aléatoire")) { this.maGrille.remplirAleatTabCases(); } else if (e.getActionCommand().equals("Chemin")) { this.etat = (byte) 0; this.indication.setEtat((byte) 0); } else if (e.getActionCommand().equals("Mur")) { this.etat = (byte) 1; this.indication.setEtat((byte) 1); } else if (e.getActionCommand().equals("Perso")) { this.etat = (byte) 2; this.indication.setEtat((byte) 2); } else if (e.getActionCommand().equals("Sortie")) { this.etat = (byte) 3; this.indication.setEtat((byte) 3); } else if (e.getActionCommand().equals("Sauvegarder")) { /* appel de la methode mapSaver */ JFileChooser chooser = new JFileChooser("./MAP/"); FileNameExtensionFilter filter = new FileNameExtensionFilter("Labyrinthe file (.lab)", "lab"); chooser.setFileFilter(filter); int returnval = chooser.showOpenDialog(null); if (returnval == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to save this file: " + chooser.getSelectedFile().getName()); MapSaver map = new MapSaver( chooser.getSelectedFile(), (byte) this.maGrille.getTaille(), this.maGrille.getPosThesee(), this.maGrille.getPosSortie(), this.maGrille.getTabCases()); } else { System.out.println("saving file aborded!"); } } else if (e.getActionCommand().equals("Retour")) { /* retour au menu precedent */ this.oldFenetre.setVisible(true); this.oldFenetre.repaint(); this.maGrille.setClosed(); } if (maGrille.estValide()) { this.sauvegarder.setEnabled(true); } else { this.sauvegarder.setEnabled(false); } }
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(); }
/* * 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; }
// 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; }
@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(); } }
@Override public void actionPerformed(ActionEvent evt) { String command = evt.getActionCommand(); switch (command) { case "New File": { OSC = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); Graphics osg = OSC.getGraphics(); osg.setColor(fillColor); osg.fillRect(0, 0, getWidth(), getHeight()); osg.dispose(); repaint(); break; } case "Open": { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG or PNG Images", "jpg", "png"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { try { OSC = ImageIO.read(chooser.getSelectedFile()); Graphics2D g2 = (Graphics2D) OSC.getGraphics(); g2.scale((double) 640 / OSC.getWidth(), (double) 480 / OSC.getHeight()); g2.drawImage(OSC, 0, 0, OSC.getWidth(), OSC.getHeight(), null); } catch (Exception e) { } } repaint(); break; } case "Save": { JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("image.PNG")); fileDialog.setDialogTitle("Select File to be Saved"); int option = fileDialog.showSaveDialog(null); if (option != JFileChooser.APPROVE_OPTION) return; // User canceled or clicked the dialog’s close box. File selectedFile = fileDialog.getSelectedFile(); if (selectedFile.exists()) { // Ask the user whether to replace the file. int response = JOptionPane.showConfirmDialog( null, "The file \"" + selectedFile.getName() + "\" already exists.\nDo you want to replace it?", "Confirm Save", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (response != JOptionPane.YES_OPTION) return; // User does not want to replace the file. } try { boolean hasFormat = ImageIO.write(OSC, "PNG", selectedFile); if (!hasFormat) throw new Exception("PNG" + " format is not available."); } catch (Exception e) { JOptionPane.showMessageDialog( null, "Sorry, an error occurred while trying to save image."); e.printStackTrace(); } break; } case "Exit": { System.exit(0); } case "Select Drawing Color...": { Color newColor = JColorChooser.showDialog(AdvancedGUIEX1.this, "Select Drawing Color", currentColor); if (newColor != null) currentColor = newColor; break; } case "Fill With Color...": { Color newColor = JColorChooser.showDialog(AdvancedGUIEX1.this, "Select Fill Color", fillColor); if (newColor != null) { fillColor = newColor; Graphics osg = OSC.getGraphics(); osg.setColor(fillColor); osg.fillRect(0, 0, OSC.getWidth(), OSC.getHeight()); osg.dispose(); AdvancedGUIEX1.this.repaint(); } break; } case "Draw With Black": currentColor = Color.BLACK; break; case "Draw With White": currentColor = Color.WHITE; break; case "Draw With Red": currentColor = Color.RED; break; case "Draw With Green": currentColor = Color.GREEN; break; case "Draw With Blue": currentColor = Color.BLUE; break; case "Draw With Yellow": currentColor = Color.YELLOW; break; case "Curve": currentTool = Tool.CURVE; break; case "Line": currentTool = Tool.LINE; break; case "Rectangle": currentTool = Tool.RECT; break; case "Oval": currentTool = Tool.OVAL; break; case "Filled Rectangle": currentTool = Tool.FILLED_RECT; break; case "Filled Oval": currentTool = Tool.FILLED_OVAL; break; case "Smudge": currentTool = Tool.SMUDGE; break; case "Erase": currentTool = Tool.ERASE; break; } }
// Initializes this component. private void jbInit() { fileChooser.setFileFilter(new ScriptFileFilter()); this.getContentPane().setLayout(null); Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>(); JLabel slowLabel = new JLabel("Slow"); slowLabel.setFont(Utilities.thinLabelsFont); JLabel fastLabel = new JLabel("Fast"); fastLabel.setFont(Utilities.thinLabelsFont); labelTable.put(1, slowLabel); labelTable.put(5, fastLabel); speedSlider.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { SpeedSlider_stateChanged(e); } }); speedSlider.setLabelTable(labelTable); speedSlider.setMajorTickSpacing(1); speedSlider.setPaintTicks(true); speedSlider.setPaintLabels(true); speedSlider.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); speedSlider.setPreferredSize(new Dimension(95, 50)); speedSlider.setMinimumSize(new Dimension(95, 50)); speedSlider.setToolTipText("Speed"); speedSlider.setMaximumSize(new Dimension(95, 50)); final Dimension buttonSize = new Dimension(39, 39); loadProgramButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { loadProgramButton_actionPerformed(); } }); loadProgramButton.setMaximumSize(buttonSize); loadProgramButton.setMinimumSize(buttonSize); loadProgramButton.setPreferredSize(buttonSize); loadProgramButton.setSize(buttonSize); loadProgramButton.setToolTipText("Load Program"); loadProgramButton.setIcon(loadProgramIcon); ffwdButton.setMaximumSize(buttonSize); ffwdButton.setMinimumSize(buttonSize); ffwdButton.setPreferredSize(buttonSize); ffwdButton.setToolTipText("Run"); ffwdButton.setIcon(ffwdIcon); ffwdButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ffwdButton_actionPerformed(); } }); stopButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { stopButton_actionPerformed(); } }); stopButton.setMaximumSize(buttonSize); stopButton.setMinimumSize(buttonSize); stopButton.setPreferredSize(buttonSize); stopButton.setToolTipText("Stop"); stopButton.setIcon(stopIcon); rewindButton.setMaximumSize(buttonSize); rewindButton.setMinimumSize(buttonSize); rewindButton.setPreferredSize(buttonSize); rewindButton.setToolTipText("Reset"); rewindButton.setIcon(rewindIcon); rewindButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { rewindButton_actionPerformed(); } }); scriptButton.setMaximumSize(buttonSize); scriptButton.setMinimumSize(buttonSize); scriptButton.setPreferredSize(buttonSize); scriptButton.setToolTipText("Load Script"); scriptButton.setIcon(scriptIcon); scriptButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { scriptButton_actionPerformed(); } }); breakButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { breakButton_actionPerformed(); } }); breakButton.setMaximumSize(buttonSize); breakButton.setMinimumSize(buttonSize); breakButton.setPreferredSize(buttonSize); breakButton.setToolTipText("Open breakpoint panel"); breakButton.setIcon(breakIcon); breakpointWindow.addBreakpointListener(this); singleStepButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { singleStepButton_actionPerformed(); } }); singleStepButton.setMaximumSize(buttonSize); singleStepButton.setMinimumSize(buttonSize); singleStepButton.setPreferredSize(buttonSize); singleStepButton.setSize(buttonSize); singleStepButton.setToolTipText("Single Step"); singleStepButton.setIcon(singleStepIcon); stepOverButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { stepOverButton_actionPerformed(); } }); stepOverButton.setMaximumSize(buttonSize); stepOverButton.setMinimumSize(buttonSize); stepOverButton.setPreferredSize(buttonSize); stepOverButton.setSize(buttonSize); stepOverButton.setToolTipText("Step Over"); stepOverButton.setIcon(stepOverIcon); animationCombo.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { animationCombo_actionPerformed(); } }); formatCombo.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { formatCombo_actionPerformed(); } }); additionalDisplayCombo.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { additionalDisplayCombo_actionPerformed(); } }); messageLbl.setFont(Utilities.statusLineFont); messageLbl.setBorder(BorderFactory.createLoweredBevelBorder()); messageLbl.setBounds(new Rectangle(0, 667, CONTROLLER_WIDTH - 8, 25)); toolBar = new JToolBar(); toolBar.setSize(new Dimension(TOOLBAR_WIDTH, TOOLBAR_HEIGHT)); toolBar.setLayout(new FlowLayout(FlowLayout.LEFT, 3, 0)); toolBar.setFloatable(false); toolBar.setLocation(0, 0); toolBar.setBorder(BorderFactory.createEtchedBorder()); arrangeToolBar(); this.getContentPane().add(toolBar, null); toolBar.revalidate(); toolBar.repaint(); repaint(); // Creating the menu bar menuBar = new JMenuBar(); arrangeMenu(); setJMenuBar(menuBar); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.getContentPane().add(messageLbl, null); setControllerSize(); // sets the frame to be visible. setVisible(true); }
public void saveUnsaved() throws SaveAbortedException { if (!saved) { int option = 0; if (loadedFile == null) option = JOptionPane.showConfirmDialog( this, new JLabel("Save changes to UNTITLED?"), "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); else option = JOptionPane.showConfirmDialog( this, new JLabel("Save changes to " + loadedFile.getName() + "?"), "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.YES_OPTION) { if (loadedFile == null) // SAVE NEW FILE { if (nameTF.getText().equals("")) { JOptionPane.showMessageDialog( this, new JLabel("Please type in the Scale Name"), "Warning", JOptionPane.WARNING_MESSAGE); throw new SaveAbortedException(); } fileChooser.setFileFilter(filter); int option2 = fileChooser.showSaveDialog(this); if (option2 == JFileChooser.APPROVE_OPTION) { File target = fileChooser.getSelectedFile(); try { PrintStream stream = new PrintStream(new FileOutputStream(target), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } else throw new SaveAbortedException(); ; } else // save LOADED FILE { try { PrintStream stream = new PrintStream(new FileOutputStream(loadedFile), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } } else if (option == JOptionPane.CANCEL_OPTION) throw new SaveAbortedException(); ; } }
public void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); if (b.getText() == "PLAY") { if (scoreP != null) scoreP.playScale(sp.getScale(), tempoP.getValue()); } else if (b.getText() == "New") { try { saveUnsaved(); } catch (SaveAbortedException ex) { return; } sp.notes.removeAllElements(); sp.repaint(); nameTF.setText(""); loadedFile = null; } else if (b.getText() == "Save") { if (nameTF.getText().equals("")) { JOptionPane.showMessageDialog( this, new JLabel("Please type in the Scale Name"), "Warning", JOptionPane.WARNING_MESSAGE); return; } fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { File target = fileChooser.getSelectedFile(); if (target.getName().indexOf(".scl") == -1) target = new File(target.getPath() + ".scl"); try { PrintStream stream = new PrintStream(new FileOutputStream(target), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } } else if (b.getText() == "Load") { try { saveUnsaved(); } catch (SaveAbortedException ex) { return; } fileChooser.setFileFilter(filter); int option = fileChooser.showOpenDialog(this); if (option == JFileChooser.APPROVE_OPTION) { loadedFile = fileChooser.getSelectedFile(); SAXParserFactory factory = SAXParserFactory.newInstance(); ScaleParser handler = new ScaleParser(false); try { SAXParser parser = factory.newSAXParser(); parser.parse(loadedFile, handler); // System.out.println("success"); } catch (Exception ex) { // System.out.println("no!!!!!! exception: "+e); // System.out.println(ex.getMessage()); ex.printStackTrace(); } // -----now :P:P--------------- System.out.println("name: " + handler.getName()); nameTF.setText(handler.getName()); sp.notes.removeAllElements(); int[] scale = handler.getScale(); for (int i = 0; i < scale.length; i++) { sp.addNote(scale[i]); } sp.repaint(); } else loadedFile = null; } }
/** * @param a * @param cnc_a */ public String save_listener(String description, String[] extensions) { String tempPath = null; boolean ovrwrtNO = false; int desn = 1; do { JFileChooser sav_c = new JFileChooser(); FileFilter filter = new FileNameExtensionFilter(description, extensions); sav_c.setFileFilter(filter); int rVal = sav_c.showSaveDialog(frame); if (rVal == JFileChooser.APPROVE_OPTION) { tempPath = sav_c.getSelectedFile().getPath(); for (String iter : extensions) { if (!tempPath.endsWith(iter)) { tempPath = tempPath + "." + iter; break; } } File f = new File(tempPath); if (f.exists()) { int ovrwrt = 1000; // random value try { ovrwrt = JOptionPane.showConfirmDialog( sav_c.getClass().newInstance(), "Do you want to overwrite the existing file", "File already exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); } catch (InstantiationException ex) { Logger.getLogger(MainEditor.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MainEditor.class.getName()).log(Level.SEVERE, null, ex); } if (ovrwrt == JOptionPane.YES_OPTION) { try { f.createNewFile(); ovrwrtNO = false; /* else { desn=0; JOptionPane.showMessageDialog(sav_c, "The file cannot be accessed", "File Protected", JOptionPane.ERROR_MESSAGE); this.actionPerformed(e); }*/ } catch (IOException ex) { Logger.getLogger(MainEditor.class.getName()).log(Level.SEVERE, null, ex); } } else { desn = 0; ovrwrtNO = true; } System.out.println("There"); } else { try { f.createNewFile(); ovrwrtNO = false; } catch (IOException ex) { Logger.getLogger(MainEditor.class.getName()).log(Level.SEVERE, null, ex); } } } else { desn = 0; ovrwrtNO = false; } } while (ovrwrtNO); if (desn == 0) { tempPath = null; } return tempPath; }
/** * Create JPanel asking users to select the file or directory containing files to be mapped and an * existing mapping file if they have one. * * @return JPanel containing elements! */ private JLayeredPane createSelectFilesPanel() { // create overall panel final JPanel selectFilesContainer = new JPanel(); selectFilesContainer.setSize(new Dimension(400, 100)); selectFilesContainer.setLayout(new BoxLayout(selectFilesContainer, BoxLayout.PAGE_AXIS)); // create selector for mapping files final FileSelectionPanel fileToMapFSP = new FileSelectionPanel( "<html>please select file(s) to be mapped (txt, csv or xls (Excel). Please ensure " + "that this file has <b>no empty columns</b> and if possible, please remove any special characters, e.g. μ</html>", fileChooser); selectFilesContainer.add(fileToMapFSP); JPanel selectMappingPanel = new JPanel(); selectMappingPanel.setLayout(new BoxLayout(selectMappingPanel, BoxLayout.PAGE_AXIS)); selectMappingPanel.setOpaque(false); // need a jcheckbox to ask users if they wish to use a mapping JPanel useMappingContainer = new JPanel(new BorderLayout()); useMappingContainer.setOpaque(false); // need a file selection panel to select the file. JFileChooser mappingFileChooser = new JFileChooser(); mappingFileChooser.setDialogTitle("Choose mapping file (XML)"); mappingFileChooser.setApproveButtonText("select file"); mappingFileChooser.setFont(UIHelper.VER_11_PLAIN); mappingFileChooser.setFileFilter(new CustomizableFileFilter("xml")); final FileSelectionPanel savedMappingsFile = new FileSelectionPanel( "<html>please select saved mapping file (xml): </html>", mappingFileChooser); savedMappingsFile.setVisible(false); final JCheckBox useMapping = new JCheckBox("use a previous mapping?"); UIHelper.renderComponent(useMapping, UIHelper.VER_11_BOLD, UIHelper.GREY_COLOR, false); useMapping.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { savedMappingsFile.setVisible(useMapping.isSelected()); } }); useMappingContainer.add(useMapping, BorderLayout.WEST); selectMappingPanel.add(useMappingContainer); selectMappingPanel.add(savedMappingsFile); selectFilesContainer.add(selectMappingPanel); final RoundedJTextField rowOffset = new RoundedJTextField(3); rowOffset.setEnabled(false); rowOffset.setSize(new Dimension(20, 20)); rowOffset.setText("1"); final JCheckBox overrideRowPosition = new JCheckBox("override row start position?"); UIHelper.renderComponent(overrideRowPosition, UIHelper.VER_11_BOLD, UIHelper.GREY_COLOR, false); overrideRowPosition.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { rowOffset.setEnabled(overrideRowPosition.isSelected()); } }); Box fileInputPanel = Box.createHorizontalBox(); fileInputPanel.setSize(new Dimension(100, 20)); fileInputPanel.add(overrideRowPosition); fileInputPanel.add(Box.createHorizontalStrut(5)); fileInputPanel.add(rowOffset); selectFilesContainer.add(fileInputPanel); selectFilesContainer.add(selectMappingPanel); final JCheckBox mapToBlankFieldsCheckbox = new JCheckBox("Do not remove blank fields?", false); UIHelper.renderComponent( mapToBlankFieldsCheckbox, UIHelper.VER_11_BOLD, UIHelper.GREY_COLOR, false); mapToBlankFieldsCheckbox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { mapToBlankFields = mapToBlankFieldsCheckbox.isSelected(); } }); JPanel removeBlanksContainer = new JPanel(new BorderLayout()); removeBlanksContainer.setOpaque(false); removeBlanksContainer.add(mapToBlankFieldsCheckbox, BorderLayout.WEST); selectFilesContainer.add(removeBlanksContainer); JPanel statusPanel = new JPanel(new GridLayout(1, 1)); statusPanel.setPreferredSize(new Dimension(400, 30)); final JLabel statusLab = UIHelper.createLabel("", UIHelper.VER_11_BOLD, UIHelper.RED_COLOR); statusPanel.add(statusLab); selectFilesContainer.add(statusPanel); final JLayeredPane finalLayout = getGeneralLayout(selectFilesHeader, breadcrumb1, "", selectFilesContainer, getHeight()); final MouseListener[] listeners = new MouseListener[2]; listeners[0] = new MouseAdapter() { public void mouseEntered(MouseEvent mouseEvent) { backButton.setIcon(backOver); } public void mouseExited(MouseEvent mouseEvent) { backButton.setIcon(back); } public void mousePressed(MouseEvent mouseEvent) { backButton.setIcon(back); SwingUtilities.invokeLater( new Runnable() { public void run() { ApplicationManager.getCurrentApplicationInstance().setCurrentPage(menuPanels); ApplicationManager.getCurrentApplicationInstance() .setGlassPanelContents(menuPanels.getCreateISAMenuGUI()); menuPanels.startAnimation(); } }); } }; assignListenerToLabel(backButton, listeners[0]); listeners[1] = new MouseAdapter() { public void mouseEntered(MouseEvent mouseEvent) { nextButton.setIcon(nextOver); } public void mouseExited(MouseEvent mouseEvent) { nextButton.setIcon(next); } public void mousePressed(MouseEvent mouseEvent) { nextButton.setIcon(next); Thread loadFile = new Thread( new Runnable() { public void run() { ISAcreatorProperties.setProperty( "isacreator.rowOffset", rowOffset.isEnabled() ? rowOffset.getText() : "1"); if (useMapping.isSelected()) { if (!savedMappingsFile.getSelectedFilePath().trim().equals("")) { MappingXMLLoader loader = new MappingXMLLoader(savedMappingsFile.getSelectedFilePath()); try { preExistingMapping = loader.loadMappings(); } catch (XmlException e) { log.error(e.getMessage()); statusLab.setText( "<html>problem found in xml for saved mapping: " + e.getMessage() + " </html>"); setCurrentPage(lastPage); return; } catch (IOException e) { log.error(e.getMessage()); statusLab.setText( "<html>problem found when resolving file for saved mapping: " + e.getMessage() + " </html>"); setCurrentPage(lastPage); return; } } else { statusLab.setText( "<html>please select a file containing previous mappings...</html>"); setCurrentPage(lastPage); return; } } else { log.info("Mapping is not selected"); statusLab.setText(""); } if (fileToMapFSP.notEmpty()) { previousPage.push(new HistoryComponent(finalLayout, listeners)); statusLab.setText(""); SwingUtilities.invokeLater( new Runnable() { public void run() { setCurrentPage( createAssayUsedPanel(fileToMapFSP.getSelectedFilePath())); } }); } else { statusLab.setText( "<html>please <strong>select</strong> a file to map!</html>"); setCurrentPage(lastPage); } } }); if (fileToMapFSP.notEmpty() && fileToMapFSP.checkFileExtensionValid("xls", "csv", "txt")) { statusLab.setText(""); lastPage = currentPage; setCurrentPage(workingProgressScreen); loadFile.start(); } else { statusLab.setText( "<html>please select a file with the extension <strong>.xls</strong>, <strong>.csv</strong> or <strong>.txt</strong>...</html>"); } } }; assignListenerToLabel(nextButton, listeners[1]); return finalLayout; }
public void actionPerformed(ActionEvent e) { if (isDirectorySelected()) { File dir = getDirectory(); if (dir != null) { try { // Strip trailing ".." dir = ShellFolder.getNormalizedFile(dir); } catch (IOException ex) { // Ok, use f as is } changeDirectory(dir); return; } } JFileChooser chooser = getFileChooser(); String filename = getFileName(); FileSystemView fs = chooser.getFileSystemView(); File dir = chooser.getCurrentDirectory(); if (filename != null) { // Remove whitespaces from end of filename int i = filename.length() - 1; while (i >= 0 && filename.charAt(i) <= ' ') { i--; } filename = filename.substring(0, i + 1); } if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; } File selectedFile = null; File[] selectedFiles = null; // Unix: Resolve '~' to user's home directory if (File.separatorChar == '/') { if (filename.startsWith("~/")) { filename = System.getProperty("user.home") + filename.substring(1); } else if (filename.equals("~")) { filename = System.getProperty("user.home"); } } if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { List<File> fList = new ArrayList<File>(); String[] files = filename.substring(1, filename.length() - 1).split("\" \""); // Optimize searching files by names in "children" array Arrays.sort(files); File[] children = null; int childIndex = 0; for (String str : files) { File file = fs.createFileObject(str); if (!file.isAbsolute()) { if (children == null) { children = fs.getFiles(dir, false); Arrays.sort(children); } for (int k = 0; k < children.length; k++) { int l = (childIndex + k) % children.length; if (children[l].getName().equals(str)) { file = children[l]; childIndex = l + 1; break; } } } fList.add(file); } if (!fList.isEmpty()) { selectedFiles = fList.toArray(new File[fList.size()]); } resetGlobFilter(); } else { selectedFile = fs.createFileObject(filename); if (!selectedFile.isAbsolute()) { selectedFile = fs.getChild(dir, filename); } // check for wildcard pattern FileFilter currentFilter = chooser.getFileFilter(); if (!selectedFile.exists() && isGlobPattern(filename)) { changeDirectory(selectedFile.getParentFile()); if (globFilter == null) { globFilter = new GlobFilter(); } try { globFilter.setPattern(selectedFile.getName()); if (!(currentFilter instanceof GlobFilter)) { actualFileFilter = currentFilter; } chooser.setFileFilter(null); chooser.setFileFilter(globFilter); return; } catch (PatternSyntaxException pse) { // Not a valid glob pattern. Abandon filter. } } resetGlobFilter(); // Check for directory change action boolean isDir = (selectedFile != null && selectedFile.isDirectory()); boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); boolean isCtrl = (e != null && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0); if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { changeDirectory(selectedFile); return; } else if ((isDir || !isFileSelEnabled) && (!isDir || !isDirSelEnabled) && (!isDirSelEnabled || selectedFile.exists())) { selectedFile = null; } } if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { selectedFiles = new File[] {selectedFile}; } chooser.setSelectedFiles(selectedFiles); // Do it again. This is a fix for bug 4949273 to force the // selected value in case the ListSelectionModel clears it // for non-existing file names. chooser.setSelectedFiles(selectedFiles); } else { chooser.setSelectedFile(selectedFile); } chooser.approveSelection(); } else { if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } chooser.cancelSelection(); } }
public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == binfo) { JOptionPane.showMessageDialog( frame, "Programme crée par Sarathai\n" + "Licence creative commons\n" + "\n" + "Pour envoyer des fichiers sur le serveur, cliquer d'abord sur le bouton ajouter,\n" + "puis sélectionnez le dossier ou fichier à ajouter. Répétez cette opération autant de foi que nécessaire.\n" + "Puis cliquez sur le bouton envoyer en ayant d'abord rempli les champs de l'adresse ip et du port.\n" + "\n" + "Pour recevoir des fichiers sauvegardés sur le serveur, cliquez sur le bouton recevoir,\n" + "puis sélectionnez le ou les fichier(s) voulu(s) dans la liste de gauche, et enfin recliquez\n" + "sur le bouton recevoir pour importer les fichiers.\n" + "\n" + "Pour toutes les infos, bien lire le texte qui s'affiche dans le champ de texte en bas.", "Informations", JOptionPane.INFORMATION_MESSAGE); } else if (src == ajouter) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(chooser.getAcceptAllFileFilter()); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int i = chooser.showOpenDialog(Fenetre.frame); if (i == JFileChooser.APPROVE_OPTION) { frame.setCursor(waitCursor); File file = chooser.getSelectedFile(); if (file.isDirectory()) { name = file.getAbsolutePath().toString() + sep; selection.addElement(name); new WhatIDo("Ajouté à la séléction", name); } else { name = file.getAbsolutePath().toString(); selection.addElement(name); new WhatIDo("Ajouté à la séléction", name); } liste.updateUI(); enlever.setEnabled(true); frame.setCursor(Cursor.getDefaultCursor()); } } else if (src == enlever) { try { int j = liste.getSelectedIndex(); new WhatIDo("Supprimé de la séléction", selection.elementAt(j).toString()); selection.removeElementAt(j); } catch (ArrayIndexOutOfBoundsException e1) { new WhatIDo("Supprimé de la séléction", selection.elementAt(0).toString()); selection.removeElementAt(0); } if (selection.size() == 0) { selection.clear(); liste.clearSelection(); enlever.setEnabled(false); } liste.updateUI(); } else if (src == bquitter) { System.exit(0); } else if (src == bnouveau) { selection.clear(); liste.clearSelection(); liste.updateUI(); new WhatIDo("Nouvelle sauvegarde"); } else if (src == benvoyer) { if (!selection.isEmpty()) { new Envoyer(selection); } else { new WhatIDo("Veuillez ajouter des fichiers ou dossiers"); } } else if (src == brecevoir) { if (!liste.isSelectionEmpty()) { Vector<String> vec = new Vector<String>(); for (int i : liste.getSelectedIndices()) { vec.addElement(selection.elementAt(i)); } new Recevoir(vec); } else { new Recevoir(); } } }
public ImageLabFrame() { // Set up menus JMenuBar menuBar = new JMenuBar(); JMenu imageLabMenu = new JMenu("imageLab"); menuBar.add(imageLabMenu); aboutItem = new JMenuItem("About imageLab"); imageLabMenu.add(aboutItem); quitItem = new JMenuItem("Quit"); imageLabMenu.add(quitItem); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); openItem = new JMenuItem("Open File..."); fileMenu.add(openItem); saveItem = new JMenuItem("Save As..."); fileMenu.add(saveItem); JMenu imageMenu = new JMenu("Images"); menuBar.add(imageMenu); addPictureGenerator(imageMenu, new Stripe()); JMenu filterMenu = new JMenu("Filters"); menuBar.add(filterMenu); addFilter(filterMenu, new BWFilter()); filterMenu.addSeparator(); addScalableFilter(filterMenu, new SwirlFilter()); // Listeners for filters are added in addScalableFilter aboutItem.addActionListener(this); quitItem.addActionListener(this); openItem.addActionListener(this); saveItem.addActionListener(this); // Set up rest of GUI lab = initialImage().getJLabel(); slider = new JSlider(0, 100); sliderPanel = new JPanel(); sliderPanel.add(slider); sliderPanel.setVisible(false); Border b1 = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); border = BorderFactory.createTitledBorder(b1, ""); sliderPanel.setBorder(border); slider.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { double scale = (slider.getValue() - 50) / 50.0; currentFilter.apply(pic1, pic2, scale); lab.setIcon(pic2.getJLabel().getIcon()); repaint(); } }); JPanel panel = new JPanel(new BorderLayout()); getContentPane().add(panel); panel.add(lab, BorderLayout.NORTH); panel.add(sliderPanel, BorderLayout.SOUTH); setJMenuBar(menuBar); pack(); setTitle("imageLab"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Prepare file chooser chooser = new JFileChooser(new File(".")); FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG Images", "jpg"); chooser.setFileFilter(filter); }
Port(Main frame, final int mode, String[] id) { super(NAME[mode] + "数据"); setSize(370, 200); setLocationRelativeTo(frame); setResizable(false); this.frame = frame; this.id = id; this.mode = mode; getContentPane().setLayout(null); JLabel csvLabel = new JLabel("CSV文件:"); csvLabel.setBounds(30, 35, 63, 16); getContentPane().add(csvLabel); JLabel picLabel = new JLabel("照片文件夹:"); picLabel.setBounds(30, 75, 78, 16); getContentPane().add(picLabel); csvField = new JTextField(); csvField.setBounds(120, 30, 134, 28); getContentPane().add(csvField); csvField.setColumns(10); csvLabel.setLabelFor(csvField); picField = new JTextField(); picField.setBounds(120, 70, 134, 28); getContentPane().add(picField); picField.setColumns(10); picLabel.setLabelFor(picField); final JButton csvButton = new JButton("选取..."); csvButton.setBounds(266, 30, 80, 29); getContentPane().add(csvButton); final JFileChooser csvChooser = new JFileChooser(); csvChooser.setFileFilter( new FileFilter() { @Override public boolean accept(File file) { boolean flag = false; if (file.isDirectory() || file.toString().endsWith(".csv")) flag = true; return flag; } @Override public String getDescription() { return "CSV 逗号分割的文件"; } }); csvButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int result; if (mode == 0) result = csvChooser.showOpenDialog(Port.this); else result = csvChooser.showSaveDialog(Port.this); if (result == JFileChooser.APPROVE_OPTION) csvField.setText(csvChooser.getSelectedFile().toString()); } }); final JButton picButton = new JButton("选取..."); picButton.setBounds(266, 70, 80, 29); getContentPane().add(picButton); final JFileChooser picChooser = new JFileChooser(); picChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); picButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int result; if (mode == 0) result = picChooser.showOpenDialog(Port.this); else result = picChooser.showSaveDialog(Port.this); if (result == JFileChooser.APPROVE_OPTION) picField.setText(picChooser.getSelectedFile().toString()); } }); progressBar = new JProgressBar(); progressBar.setBounds(30, 130, 160, 20); getContentPane().add(progressBar); final JButton button = new JButton("开始"); button.setBounds(230, 126, 117, 29); getContentPane().add(button); getRootPane().setDefaultButton(button); button.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { csvFile = new File(csvField.getText()); picDirectory = new File(picField.getText()); if (mode == 0) { if (!csvFile.exists() || csvFile.isDirectory() || !picDirectory.isDirectory()) { JOptionPane.showMessageDialog( Port.this, "请选择正确的文件", "注意", JOptionPane.INFORMATION_MESSAGE); return; } } else if (csvFile.exists() || (picDirectory.exists() && !picDirectory.isDirectory()) || csvFile.getPath().equals(picDirectory.getPath())) { JOptionPane.showMessageDialog( Port.this, "文件已存在", "注意", JOptionPane.INFORMATION_MESSAGE); return; } button.setEnabled(false); csvButton.setEnabled(false); picButton.setEnabled(false); csvField.setEnabled(false); picField.setEnabled(false); if (mode == 0) new Import().start(); else new Export().start(); } }); setVisible(true); }
public ImageViewerFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // set up menu bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu menu = new JMenu("File"); menuBar.add(menu); JMenuItem openItem = new JMenuItem("Open"); menu.add(openItem); openItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { chooser.setCurrentDirectory(new File(".")); // show file chooser dialog int result = chooser.showOpenDialog(ImageViewerFrame.this); // if image file accepted, set it as icon of the label if (result == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); label.setIcon(new ImageIcon(name)); pack(); } } }); JMenuItem exitItem = new JMenuItem("Exit"); menu.add(exitItem); exitItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); // use a label to display the images label = new JLabel(); add(label); // set up file chooser chooser = new JFileChooser(); // accept all image files ending with .jpg, .jpeg, .gif /* final ExtensionFileFilter filter = new ExtensionFileFilter(); filter.addExtension("jpg"); filter.addExtension("jpeg"); filter.addExtension("gif"); filter.setDescription("Image files"); */ FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif"); chooser.setFileFilter(filter); chooser.setAccessory(new ImagePreviewer(chooser)); chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif"))); }