This option will reset the home page of this site. Restoring any closed widgets or categories.

Reset

Cara membuat file chooser di Java

Dalam sebuah aplikasi berbasis java, kadang kita memerlukan sebuah interface untuk membaca/membuka sebuah file. Untuk melakukan hal tersebut kita dapat memanfaatkan class “JFileChooser” milik java, kemudian kita berikan filter sehingga hanya file-file tertentu saja yang dapat dibuka/dibaca misal: file *.txt. Pada kesempatan kali ini saya menggunakan editor Netbeans IDE 6.5.1 untuk membuat interface nya, silakan ikuti langkah-langkah dibawah ini:

  1. Buat sebuah file baru pada project anda dengan cara meng-klik kanan pada project >> new >> JFrame
  2. Selanjutnya tambahkan JTextField/textbox,JButton,dan JTextArea
  3. Berikan sebuah event pada JButton dengan cara klik kanan pada JButton >> Events >> Action >>Action Performed. Tambahkan kode berikut :
 JFileChooser chooser = new JFileChooser("C:\\");
 FileNameExtensionFilter filter=new FileNameExtensionFilter("SQL FILE","sql","txt","TXT");
 chooser.addChoosableFileFilter(filter);
 chooser.setDialogTitle("Pilih File...");
 int opt = chooser.showOpenDialog(this);
 String dir = chooser.getSelectedFile().getAbsolutePath();
 String newString = dir.replace('\\', '/');
 String myStr = dir + "\\" + ((chooser.getSelectedFile() != null) ? chooser.getSelectedFile().getName() : "nothing");
 txtPath.setText(newString);
 if (opt == chooser.APPROVE_OPTION) {
 try {
 isiFile.setText("");
 reader = new BufferedReader(new FileReader(newString));
 try {
 while ((data = reader.readLine()) != null) {
 isiFile.append(data+"\n");
 isiFile.setWrapStyleWord(true);
 }
 } catch (IOException ex) {
 Logger.getLogger(bacaFile.class.getName()).log(Level.SEVERE, null, ex);
 }
 } catch (FileNotFoundException ex) {
 Logger.getLogger(bacaFile.class.getName()).log(Level.SEVERE, null, ex);
 }
 }

Source Code selengkapnya :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * bacaFile.java
 *
 * Created on Mar 10, 2009, 8:42:32 PM
 */
package paket_aplikasiNilai;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
 *
 * @author lambang
 */
public class bacaFile extends javax.swing.JFrame {
 private String data;
 private BufferedReader reader;
 /** Creates new form bacaFile */
 public bacaFile() {
 initComponents();
 }
 @SuppressWarnings("unchecked")
 // kode yg digenerate oleh Netbeans
 private void initComponents() {
 jPanel1 = new javax.swing.JPanel();
 txtPath = new javax.swing.JTextField();
 btnBrowse = new javax.swing.JButton();
 jScrollPane1 = new javax.swing.JScrollPane();
 isiFile = new javax.swing.JTextArea();
 setTitle("BACA FILE");
 setResizable(false);
 jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new org.jvnet.substance.utils.border.SubstanceEtchedBorder(), "File Directory", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("FreeSans", 1, 11))); // NOI18N
 jPanel1.setName("jPanel1"); // NOI18N
 txtPath.setFont(new java.awt.Font("Tahoma", 1, 12));
 txtPath.setForeground(new java.awt.Color(255, 0, 0));
 txtPath.setName("txtPath"); // NOI18N
 btnBrowse.setText("Browse");
 btnBrowse.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
 btnBrowse.setIconTextGap(5);
 btnBrowse.setName("btnBrowse"); // NOI18N
 btnBrowse.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 btnBrowseActionPerformed(evt);
 }
 });
 javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
 jPanel1.setLayout(jPanel1Layout);
 jPanel1Layout.setHorizontalGroup(
 jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(jPanel1Layout.createSequentialGroup()
 .addContainerGap()
 .addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(btnBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addContainerGap(105, Short.MAX_VALUE))
 );
 jPanel1Layout.setVerticalGroup(
 jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
 .addComponent(btnBrowse, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
 .addComponent(txtPath, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
 .addContainerGap())
 );
 jScrollPane1.setName("jScrollPane1"); // NOI18N
 isiFile.setColumns(60);
 isiFile.setFont(new java.awt.Font("Courier New", 0, 13)); // NOI18N
 isiFile.setForeground(new java.awt.Color(0, 102, 204));
 isiFile.setRows(10);
 isiFile.setName("isiFile"); // NOI18N
 jScrollPane1.setViewportView(isiFile);
 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
 getContentPane().setLayout(layout);
 layout.setHorizontalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addContainerGap()
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
 .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE))
 .addGap(18, 18, 18))
 );
 layout.setVerticalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addGap(17, 17, 17)
 .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addContainerGap(30, Short.MAX_VALUE))
 );
 pack();
 }// Akhir kode yg digenerate Netbeans
 private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {
 // TODO add your handling code here:
 JFileChooser chooser = new JFileChooser("C:\\");
 FileNameExtensionFilter filter=new FileNameExtensionFilter("SQL FILE","sql","txt","TXT");
 chooser.addChoosableFileFilter(filter);
 chooser.setDialogTitle("Pilih File...");
 int opt = chooser.showOpenDialog(this);
 String dir = chooser.getSelectedFile().getAbsolutePath();
 String newString = dir.replace('\\', '/');
 String myStr = dir + "\\" + ((chooser.getSelectedFile() != null) ? chooser.getSelectedFile().getName() : "nothing");
 txtPath.setText(newString);
 if (opt == chooser.APPROVE_OPTION) {
 try {
 isiFile.setText("");
 reader = new BufferedReader(new FileReader(newString));
 try {
 while ((data = reader.readLine()) != null) {
 isiFile.append(data+"\n");
 isiFile.setWrapStyleWord(true);
 }
 } catch (IOException ex) {
 Logger.getLogger(bacaFile.class.getName()).log(Level.SEVERE, null, ex);
 }
 } catch (FileNotFoundException ex) {
 Logger.getLogger(bacaFile.class.getName()).log(Level.SEVERE, null, ex);
 }
 }
 }
 public static void main(String args[]) throws ClassNotFoundException {
 try {
 UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel");
 java.awt.EventQueue.invokeLater(new Runnable() {
 public void run() {
 bacaFile login=new bacaFile();
 login.pack();
 login.setVisible(true);
 }
 });
 }catch(Exception ex){
 }
 }
 // Variables declaration - do not modify
 private javax.swing.JButton btnBrowse;
 private javax.swing.JTextArea isiFile;
 private javax.swing.JPanel jPanel1;
 private javax.swing.JScrollPane jScrollPane1;
 private javax.swing.JTextField txtPath;
 // End of variables declaration
}



Leave a Reply

Security Code: