Monday 8 September 2014

File Chooser in Java NetBeans

Structure of the Problem Requirements

In this problem we will learn how to make a file chooser in Java NetBeans IDE. Through File Chooser we can browse the files in our system and select a specific file. In this program we make an interface in which there is one text field and we have 3 buttons Load, Save, Browse. When user click on browse button then the file chooser is open and user can select a file, when click on load then all the text from file is copied and it shown on text area and save button save the user text in the given text filed. Here is the source code of this problem which help you in better understanding.

Source Code



importjava.awt.HeadlessException;
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
import java.io.File;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;
importjavax.swing.JFileChooser;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author LEP
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        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">                         
    private voidinitComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        text = new javax.swing.JTextArea();
        load = new javax.swing.JButton();
        save = new javax.swing.JButton();
        bBrowse = new javax.swing.JButton();
        lBrowseFile = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(0, 204, 0));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 32)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 51));
        jLabel1.setText("Java IO");
        jPanel1.add(jLabel1);

        getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);

        jPanel2.setBackground(new java.awt.Color(255, 204, 0));

        text.setColumns(30);
        text.setRows(5);
        jScrollPane2.setViewportView(text);

        jPanel2.add(jScrollPane2);

        load.setText("Load");
        load.addActionListener(new java.awt.event.ActionListener() {
            public voidactionPerformed(java.awt.event.ActionEvent evt) {
                loadActionPerformed(evt);
            }
        });
        jPanel2.add(load);

        save.setText("Save");
        save.addActionListener(new java.awt.event.ActionListener() {
            public voidactionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });
        jPanel2.add(save);

        bBrowse.setText("Browse");
        bBrowse.addActionListener(new java.awt.event.ActionListener() {
            public voidactionPerformed(java.awt.event.ActionEvent evt) {
                bBrowseActionPerformed(evt);
            }
        });
        jPanel2.add(bBrowse);

        lBrowseFile.setText("D:\\text.txt");
        jPanel2.add(lBrowseFile);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>                       

    private voidloadActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        File f = new File(lBrowseFile.getText());
        if(f.exists())
        {
                try
                {
                    FileReader fr = new FileReader(f);
                    BufferedReader br = newBufferedReader(fr);
                    String s = br.readLine();
                    text.setText(s);
                }
                catch(IOException e)
                {
                    System.out.println("Error");
                }
        }
    }                                   

    private voidsaveActionPerformed(java.awt.event.ActionEvent evt) {                                    

        File f = new File(lBrowseFile.getText());
        if(f.exists())
        {
                try
                {
                    FileWriter fr = new FileWriter(f);
                    try (BufferedWriter br = newBufferedWriter(fr)) {
                        String s = text.getText();
                        br.write(text.getText());
                    }
                }
                catch(IOException e)
                {
                    System.out.println("Error");
                }
        }
    }                                   

    private voidbBrowseActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        try
        {
            JFileChooser jfc = newJFileChooser();
            jfc.showOpenDialog(this);
            File f = jfc.getSelectedFile();
            lBrowseFile.setText(f.getAbsolutePath());
        }
        catch(HeadlessException e)
        {
            System.out.println("Error");
        }
    }                                      

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton bBrowse;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lBrowseFile;
    private javax.swing.JButton load;
    private javax.swing.JButton save;
    private javax.swing.JTextArea text;
    // End of variables declaration                  
}

File Chooser
File Chooser in Java NetBeans

Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments: Post Yours! Read Comment Policy!▼
Important Note:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

  1. Small recommendation:

    Attach a file of the code rather than the whole code contained within a div on the page. It is unsightly and rather annoying to scroll through.

    ReplyDelete