Zip Archive of Source code: TextBoxWithFileOps
Type and edit normally in the text box. Load a file if you wish first. Then save off to file. Includes the use of a filechooser and a menu.
In the code below
- Main calls the class FileOpGUI and sets it visible. This must invoke all the following steps
- FileOpGUI assumes the name and initializes all the constituent pieces.
- Code at the bottom declares all the parts and pieces
- Next code after the Class declaration instantiates parts / pieces using the NEW syntax
- Some properties of the bits and pieces are set like titles
- Menu code in automatically entered but the programmer has to fill in what they do. In this case simple file ops like SAVE, OPEN
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * FileOpGUI.java * * Created on Jan 13, 2012, 2:08:15 PM */ package FileOperations; import java.io.*; //import java.util.prefs.Preferences; /** * * @author F. Sandlewould */ public class FileOpGUI extends javax.swing.JFrame { /** Creates new form FileOpGUI */ public FileOpGUI() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { fileChooser = new javax.swing.JFileChooser(); jScrollPane1 = new javax.swing.JScrollPane(); FileContentsTextArea = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); UserPromptTextArea = new javax.swing.JTextArea(); AppendTestButton = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); FileOperations = new javax.swing.JMenu(); mnuOpenFile = new javax.swing.JMenuItem(); mnuSaveFile = new javax.swing.JMenuItem(); mnuNewFile = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("File Operations"); setName("FileFrame"); // NOI18N FileContentsTextArea.setColumns(20); FileContentsTextArea.setRows(5); jScrollPane1.setViewportView(FileContentsTextArea); UserPromptTextArea.setColumns(20); UserPromptTextArea.setRows(5); UserPromptTextArea.setText("User prompt"); jScrollPane2.setViewportView(UserPromptTextArea); AppendTestButton.setText("Append"); AppendTestButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AppendTestButtonActionPerformed(evt); } }); FileOperations.setText("File"); mnuOpenFile.setText("Open"); mnuOpenFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mnuOpenFileActionPerformed(evt); } }); FileOperations.add(mnuOpenFile); mnuSaveFile.setText("Save"); mnuSaveFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mnuSaveFileActionPerformed(evt); } }); FileOperations.add(mnuSaveFile); mnuNewFile.setText("New"); mnuNewFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mnuNewFileActionPerformed(evt); } }); FileOperations.add(mnuNewFile); jMenuBar1.add(FileOperations); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 673, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 673, Short.MAX_VALUE) .addComponent(AppendTestButton, javax.swing.GroupLayout.Alignment.LEADING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(AppendTestButton) .addContainerGap(51, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents //routine needed to append a line & update file //append line to the textarea //use the SaveFile function private void mnuOpenFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuOpenFileActionPerformed fileChooser.setDialogTitle("Open SASL List"); fileChooser.setApproveButtonText("Open"); int returnVal = fileChooser.showOpenDialog(this); if (returnVal == fileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { // What to do with the file, e.g. display it in a TextArea FileContentsTextArea.read( new FileReader( file.getAbsolutePath() ), null ); UserPromptTextArea.setText( "Opening: " + "\n"+ "\r" + file.getAbsolutePath()); } catch (IOException ex) { UserPromptTextArea.setText("Problem accessing file"+file.getAbsolutePath()); } } else { UserPromptTextArea.setText("File access cancelled by user."); } }//GEN-LAST:event_mnuOpenFileActionPerformed private void mnuSaveFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSaveFileActionPerformed Writer output = null; fileChooser.setDialogTitle("Save SASL List"); fileChooser.setApproveButtonText("Save"); int returnVal = fileChooser.showOpenDialog(this); if (returnVal == fileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try{ WriteFile(file.getAbsolutePath(),FileContentsTextArea.getText()); } catch(NullPointerException ex){} } else { UserPromptTextArea.setText("File write cancelled by user."); } }//GEN-LAST:event_mnuSaveFileActionPerformed private void mnuNewFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNewFileActionPerformed //open up the file chooser > user navigates to preferred location //user enters name in file chooser text line //user clicks enter Writer output = null; fileChooser.setDialogTitle("Create new SASL log file"); fileChooser.setApproveButtonText("Save As"); int returnVal = fileChooser.showOpenDialog(this); if (returnVal == fileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try{ WriteFile(file.getAbsolutePath(),FileContentsTextArea.getText()); } catch(NullPointerException ex){} } else { UserPromptTextArea.setText("File write cancelled by user."); } }//GEN-LAST:event_mnuNewFileActionPerformed private void AppendTestButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AppendTestButtonActionPerformed AppendEntry("another line woot!"); AppendEntry("PathFileName= "); // + fileChooser.getSelectedFile().getAbsolutePath() ); <--this part causes another exception!! ( null pointer ) }//GEN-LAST:event_AppendTestButtonActionPerformed public void AppendEntry(String Line){ FileContentsTextArea.append( "\n" + Line ); //textarea -> file save try{ WriteFile(fileChooser.getSelectedFile().getAbsolutePath(),FileContentsTextArea.getText()); } catch( NullPointerException ex) { UserPromptTextArea.setText("Problem writing file > File not saved"); } }; public void WriteFile(String PathFileName, String FileContents) throws NullPointerException{ Writer output = null; try { output = new BufferedWriter(new FileWriter(PathFileName)); output.write(FileContents); output.close(); FileContentsTextArea.read( new FileReader( PathFileName ), null ); UserPromptTextArea.setText( "File saved: " + "\n"+ "\r" + PathFileName); } catch (IOException ex) { UserPromptTextArea.setText("Problem writing file"+ PathFileName); throw new NullPointerException("Cannot write file"); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FileOpGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FileOpGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FileOpGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FileOpGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FileOpGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton AppendTestButton; private javax.swing.JTextArea FileContentsTextArea; private javax.swing.JMenu FileOperations; private javax.swing.JTextArea UserPromptTextArea; private javax.swing.JFileChooser fileChooser; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JMenuItem mnuNewFile; private javax.swing.JMenuItem mnuOpenFile; private javax.swing.JMenuItem mnuSaveFile; // End of variables declaration//GEN-END:variables }
0 Comments