javadud
asked on
JFileChooser problem
Hi experts,
I am having trouble with a JFileChooser I can get the dialogbox to open ok using the following code:
public void actionPerformed(ActionEven t e){
if(e.getSource()== openItem){
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(Fra me);
if(result == JFileChooser.APPROVE_OPTIO N){
File file = chooser.getSelectedFile();
String filename = file.getName();
}else
input.setText("you cancelled the file dialog");
However I also have an input class that inputs a text file into a string tokenizer, what I would like to do is be able to use the JFileChooser to select a text file and input that into the String tokenizer, any comments would be much appreciated.
Cheers
I am having trouble with a JFileChooser I can get the dialogbox to open ok using the following code:
public void actionPerformed(ActionEven
if(e.getSource()== openItem){
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(Fra
if(result == JFileChooser.APPROVE_OPTIO
File file = chooser.getSelectedFile();
String filename = file.getName();
}else
input.setText("you cancelled the file dialog");
However I also have an input class that inputs a text file into a string tokenizer, what I would like to do is be able to use the JFileChooser to select a text file and input that into the String tokenizer, any comments would be much appreciated.
Cheers
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
It is rather for a text file. :)
ASKER
Thanks for the reply Javatm, but im still not sure how to implement this into the string tokenizer so I can search the string etc.
Or try something like this :
String record = null;
try {
BufferedReader br = new BufferedReader( new FileReader( fileName ) );
record = new String();
StringTokenizer stTok;
while ((record = br.readLine()) != null) {
stTok = new StringTokenizer(record," ");
while (stTok.hasMoreTokens()) {
System.out.println(stTok.n extToken() );
}
} // END WHILE
}
catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("IOExce ption error: ");
e.printStackTrace();
}
Hope it helps . . .
JAVATM
String record = null;
try {
BufferedReader br = new BufferedReader( new FileReader( fileName ) );
record = new String();
StringTokenizer stTok;
while ((record = br.readLine()) != null) {
stTok = new StringTokenizer(record," ");
while (stTok.hasMoreTokens()) {
System.out.println(stTok.n
}
} // END WHILE
}
catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("IOExce
e.printStackTrace();
}
Hope it helps . . .
JAVATM
Dont forget to add this into your JFileChooser :
File fileName = x.getSelectedFile();
File fileName = x.getSelectedFile();
ASKER
Think that is working, but every button I click now opens the JFileChooser???
This should do it :
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;
public class Word extends JFrame
{
private JTextArea t1;
StringTokenizer stTok;
public Word()
{
super("Word Processor . . .");
t1 = new JTextArea(30,5);
JButton b1 = new JButton("Open");
JButton b2 = new JButton("Save");
JScrollPane scroll = new JScrollPane(t1);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new FlowLayout() );
buttonPanel.add( b1 );
buttonPanel.add( b2 );
getContentPane().setLayout ( new BorderLayout() );
getContentPane().add( scroll, BorderLayout.CENTER);
getContentPane().add( buttonPanel, BorderLayout.SOUTH);
setBounds(10,10,200,50);
setSize(500, 500);
show();
b1.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
openMe();
}
});
b2.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
saveMe();
}
});
}
private void openMe()
{
JFileChooser x = new JFileChooser();
x.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = x.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION )
return;
File fileName = x.getSelectedFile();
if ( fileName == null || fileName.getName().equals( "" ) )
{
JOptionPane.showMessageDia log( this,"Select file name . . .","Warning . . .",
JOptionPane.WARNING_MESSAG E );
}
else
{
try {
BufferedReader br = new BufferedReader( new FileReader( fileName ) );
String record = new String(""+fileName);
StringTokenizer stTok;
while ((record = br.readLine()) != null) {
// Here is you String Tokenizer
stTok = new StringTokenizer(record," ");
while (stTok.hasMoreTokens()) {
System.out.println(stTok.n extToken() );
}
} // END WHILE
} catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("IOExce ption error: ");
e.printStackTrace();
}
}
}
private void saveMe()
{
JFileChooser y = new JFileChooser();
y.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = y.showSaveDialog( this );
if ( result == JFileChooser.CANCEL_OPTION )
return;
File fileName = y.getSelectedFile();
if ( fileName == null || fileName.getName().equals( "" ) )
{
JOptionPane.showMessageDia log( this,"Invalid file name . . .","Warning . . .",
JOptionPane.WARNING_MESSAG E );
}
else
{
try
{
PrintWriter pw = new PrintWriter ( new FileWriter ( fileName ) );
pw.print( t1.getText() );
pw.close();
}
catch ( Exception e )
{
JOptionPane.showMessageDia log(this," Error Saving File . . .","Warning . . .",
JOptionPane.ERROR_MESSAGE) ;
}
}
}
public static void main (String args[])
{
Word x = new Word();
x.setDefaultCloseOperation (JFrame.EX IT_ON_CLOS E);
}
}
Hope it helps . . .
JAVATM
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;
public class Word extends JFrame
{
private JTextArea t1;
StringTokenizer stTok;
public Word()
{
super("Word Processor . . .");
t1 = new JTextArea(30,5);
JButton b1 = new JButton("Open");
JButton b2 = new JButton("Save");
JScrollPane scroll = new JScrollPane(t1);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new FlowLayout() );
buttonPanel.add( b1 );
buttonPanel.add( b2 );
getContentPane().setLayout
getContentPane().add( scroll, BorderLayout.CENTER);
getContentPane().add( buttonPanel, BorderLayout.SOUTH);
setBounds(10,10,200,50);
setSize(500, 500);
show();
b1.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
openMe();
}
});
b2.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
saveMe();
}
});
}
private void openMe()
{
JFileChooser x = new JFileChooser();
x.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = x.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION
return;
File fileName = x.getSelectedFile();
if ( fileName == null || fileName.getName().equals(
{
JOptionPane.showMessageDia
JOptionPane.WARNING_MESSAG
}
else
{
try {
BufferedReader br = new BufferedReader( new FileReader( fileName ) );
String record = new String(""+fileName);
StringTokenizer stTok;
while ((record = br.readLine()) != null) {
// Here is you String Tokenizer
stTok = new StringTokenizer(record," ");
while (stTok.hasMoreTokens()) {
System.out.println(stTok.n
}
} // END WHILE
} catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("IOExce
e.printStackTrace();
}
}
}
private void saveMe()
{
JFileChooser y = new JFileChooser();
y.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = y.showSaveDialog( this );
if ( result == JFileChooser.CANCEL_OPTION
return;
File fileName = y.getSelectedFile();
if ( fileName == null || fileName.getName().equals(
{
JOptionPane.showMessageDia
JOptionPane.WARNING_MESSAG
}
else
{
try
{
PrintWriter pw = new PrintWriter ( new FileWriter ( fileName ) );
pw.print( t1.getText() );
pw.close();
}
catch ( Exception e )
{
JOptionPane.showMessageDia
JOptionPane.ERROR_MESSAGE)
}
}
}
public static void main (String args[])
{
Word x = new Word();
x.setDefaultCloseOperation
}
}
Hope it helps . . .
JAVATM
Did it work ? if not I can give you a revise codes. :)
ASKER
sorry for the slow response, I am getting an ArrayIndexOutOfBounds Exception, trying to find the error.
Are you trying to incode your own codes ?
1.) If yes, can you give your codes ?
2.) If no, try this :
/* Copyright : Javatm
http://javatm.4t.com */
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Word extends JFrame {
private JTextArea t1;
private JButton b1, b2;
public Word()
{
super("Word Processor . . .");
t1 = new JTextArea(30,50);
b1 = new JButton("Open");
b2 = new JButton("Save");
JScrollPane scroll = new JScrollPane(t1);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new FlowLayout() );
buttonPanel.add( b1 );
buttonPanel.add( b2 );
getContentPane().setLayout ( new BorderLayout() );
getContentPane().add( scroll, BorderLayout.CENTER);
getContentPane().add( buttonPanel, BorderLayout.SOUTH);
setBounds(10,10,200,50);
setSize(500, 500);
show();
b1.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
openMe();
}
});
b2.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
saveMe();
}
});
}
private void openMe()
{
JFileChooser x = new JFileChooser();
x.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = x.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION )
return;
File fileName = x.getSelectedFile();
if ( fileName == null || fileName.getName().equals( "" ) )
{
JOptionPane.showMessageDia log( this,"Select file name . . .","Warning . . .",
JOptionPane.WARNING_MESSAG E );
}
else
{
try {
BufferedReader br = new BufferedReader( new FileReader( fileName ) );
String y = new String(""+fileName);
String ext = "";
while ((y = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(""+y);
ext = ext + y + "\n";
while (st.hasMoreTokens()) {
// This will show an output on Dos
System.out.println(st.next Token());
}
}
br.close();
t1.setText( ext );
}
catch (IOException e) {
// This will show an error on Dos
System.out.println("Error on command . . .");
e.printStackTrace();
}
}
}
private void saveMe()
{
JFileChooser y = new JFileChooser();
y.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = y.showSaveDialog( this );
if ( result == JFileChooser.CANCEL_OPTION )
return;
File fileName = y.getSelectedFile();
if ( fileName == null || fileName.getName().equals( "" ) )
{
JOptionPane.showMessageDia log( this,"Invalid file name . . .","Warning . . .",
JOptionPane.WARNING_MESSAG E );
}
else
{
try {
PrintWriter pw = new PrintWriter ( new FileWriter ( fileName ) );
pw.print( t1.getText() );
pw.close();
}
catch ( Exception e ) {
JOptionPane.showMessageDia log(this," Error Saving File . . .","Warning . . .",
JOptionPane.ERROR_MESSAGE) ;
}
}
}
public static void main (String args[])
{
Word x = new Word();
x.setDefaultCloseOperation (JFrame.EX IT_ON_CLOS E);
}
}
1.) If yes, can you give your codes ?
2.) If no, try this :
/* Copyright : Javatm
http://javatm.4t.com */
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Word extends JFrame {
private JTextArea t1;
private JButton b1, b2;
public Word()
{
super("Word Processor . . .");
t1 = new JTextArea(30,50);
b1 = new JButton("Open");
b2 = new JButton("Save");
JScrollPane scroll = new JScrollPane(t1);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new FlowLayout() );
buttonPanel.add( b1 );
buttonPanel.add( b2 );
getContentPane().setLayout
getContentPane().add( scroll, BorderLayout.CENTER);
getContentPane().add( buttonPanel, BorderLayout.SOUTH);
setBounds(10,10,200,50);
setSize(500, 500);
show();
b1.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
openMe();
}
});
b2.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
saveMe();
}
});
}
private void openMe()
{
JFileChooser x = new JFileChooser();
x.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = x.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION
return;
File fileName = x.getSelectedFile();
if ( fileName == null || fileName.getName().equals(
{
JOptionPane.showMessageDia
JOptionPane.WARNING_MESSAG
}
else
{
try {
BufferedReader br = new BufferedReader( new FileReader( fileName ) );
String y = new String(""+fileName);
String ext = "";
while ((y = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(""+y);
ext = ext + y + "\n";
while (st.hasMoreTokens()) {
// This will show an output on Dos
System.out.println(st.next
}
}
br.close();
t1.setText( ext );
}
catch (IOException e) {
// This will show an error on Dos
System.out.println("Error on command . . .");
e.printStackTrace();
}
}
}
private void saveMe()
{
JFileChooser y = new JFileChooser();
y.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = y.showSaveDialog( this );
if ( result == JFileChooser.CANCEL_OPTION
return;
File fileName = y.getSelectedFile();
if ( fileName == null || fileName.getName().equals(
{
JOptionPane.showMessageDia
JOptionPane.WARNING_MESSAG
}
else
{
try {
PrintWriter pw = new PrintWriter ( new FileWriter ( fileName ) );
pw.print( t1.getText() );
pw.close();
}
catch ( Exception e ) {
JOptionPane.showMessageDia
JOptionPane.ERROR_MESSAGE)
}
}
}
public static void main (String args[])
{
Word x = new Word();
x.setDefaultCloseOperation
}
}
Dude;
I'm at work & already need to go home, thank you very much for having
sometime with me, anyways here are some research for you :
http://java.sun.com/products/jdk/1.2/docs/api/java/util/StringTokenizer.html
http://developer.java.sun.com/developer/technicalArticles/Programming/stringtokenizer/
Also try this previous topic:
http://www-level3.experts-exchange.com/questions/20681014/String-Tokenizer.html
Hope it helps . . .
JAVATM
I'm at work & already need to go home, thank you very much for having
sometime with me, anyways here are some research for you :
http://java.sun.com/products/jdk/1.2/docs/api/java/util/StringTokenizer.html
http://developer.java.sun.com/developer/technicalArticles/Programming/stringtokenizer/
Also try this previous topic:
http://www-level3.experts-exchange.com/questions/20681014/String-Tokenizer.html
Hope it helps . . .
JAVATM
ASKER
Javatm,
here is what I have gotL
private void initMenu(){
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
openItem = new JMenuItem("Open");
fileMenu.add(openItem);
openItem.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
openMe();
}
});
}
public void openMe()
{
JFileChooser x = new JFileChooser();
int result = x.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION )
return;
File fileName = x.getSelectedFile();
FileName = fileName.toString();
if ( fileName != null)
{
try {
BufferedReader inStream
= new BufferedReader(new FileReader(fileName));
String thisLine = inStream.readLine();
while (thisLine != null) {
numberOfRows++;
thisLine = inStream.readLine();
}
inStream.close();
}
catch (IOException e) {
System.out.println("A File I/O error has occured.");
}
}
try {
BufferedReader inStream
= new BufferedReader(new FileReader(fileName));
String thisLine = inStream.readLine();
details = new Customer[numberOfRows];
int row = 0;
while (thisLine != null)
{
StringTokenizer lineDetails = new StringTokenizer(thisLine," ,");
id = lineDetails.nextToken();
name = lineDetails.nextToken();
address = lineDetails.nextToken();
ph = lineDetails.nextToken();
accType = lineDetails.nextToken();
lastPurDate = lineDetails.nextToken();
maxCredit = Integer.parseInt(lineDetai ls.nextTok en());
currBalance = Integer.parseInt(lineDetai ls.nextTok en());
details[row] = new Customer(id,name,address,p h,accType, lastPurDat e,
maxCredit,currBalance);
thisLine = inStream.readLine();
row++;
}
inStream.close();
} catch (IOException e) {
System.out.println("A File I/O error has occured.");
}
}
public Customer[] getDetails() {
if (numberOfRows == 0) {
openMe();
}
return details;
}
public void actionPerformed(ActionEven t e){
if (e.getSource() == disp){
Customer [] getData = getDetails();
String getInput = custID.getText();
Keyword kw = new Keyword(getInput);
Comparator keywordCompare = new KeywordCompare();
int found = Arrays.binarySearch(getDat a,kw,keywo rdCompare) ;
if(found>=0){
custName.setText(getData[f ound].name );
custPh.setText(getData[fou nd].ph);
String maxCredit = new Integer(getData[found].max Cred).toSt ring();
String currBalance = new Integer(getData[found].cur rBal).toSt ring();
currBal.setText(currBalanc e);
maxCred.setText(maxCredit) ;
custAcc.setText(getData[fo und].accTy pe);
custAddress.setText(getDat a[found].a ddress);
custLastPurchase.setText(g etData[fou nd].lastPu rDate);
}
else {
custID.setText("not found");
custName.setText("");
custPh.setText("");
currBal.setText("");
maxCred.setText("");
custAcc.setText("");
custAddress.setText("");
custLastPurchase.setText(" ");
}
}
if (e.getSource() == add){
getDetails();
String [] det ={custID.getText(), custName.getText(), custAddress.getText(),
custPh.getText(), custAcc.getText(), custLastPurchase.getText() ,
maxCred.getText(), currBal.getText()};
writeTextFile(det);
}
}
public void writeTextFile(String det[]) {
try {
FileWriter outfileWrite = new FileWriter(FileName, true);
BufferedWriter outBufferedWrite = new BufferedWriter(outfileWrit e);
for(int i=0; i<det.length-1; ++i)
{ outBufferedWrite.write(det [i] +",");
}
outBufferedWrite.write(det [det.lengt h-1]);
outBufferedWrite.newLine() ;
outBufferedWrite.close();
} catch (IOException e) {
System.out.println("IOERRO R: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
public static void main(String args[]) {
System.out.println("Starti ng Mon_suppliers_app...");
Monsupp mainFrame = new Monsupp();
mainFrame.setSize(850, 300);
mainFrame.setTitle("Mon_su ppliers_ap p");
mainFrame.setVisible(true) ;
}
}
Its working except when i add new customer details I cannot redisplay them in the same session I need to somehow re-read the textfile when the display button is pushed. Any Ideas?
Thanks
here is what I have gotL
private void initMenu(){
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
openItem = new JMenuItem("Open");
fileMenu.add(openItem);
openItem.addActionListener
{
public void actionPerformed( ActionEvent ae )
{
openMe();
}
});
}
public void openMe()
{
JFileChooser x = new JFileChooser();
int result = x.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION
return;
File fileName = x.getSelectedFile();
FileName = fileName.toString();
if ( fileName != null)
{
try {
BufferedReader inStream
= new BufferedReader(new FileReader(fileName));
String thisLine = inStream.readLine();
while (thisLine != null) {
numberOfRows++;
thisLine = inStream.readLine();
}
inStream.close();
}
catch (IOException e) {
System.out.println("A File I/O error has occured.");
}
}
try {
BufferedReader inStream
= new BufferedReader(new FileReader(fileName));
String thisLine = inStream.readLine();
details = new Customer[numberOfRows];
int row = 0;
while (thisLine != null)
{
StringTokenizer lineDetails = new StringTokenizer(thisLine,"
id = lineDetails.nextToken();
name = lineDetails.nextToken();
address = lineDetails.nextToken();
ph = lineDetails.nextToken();
accType = lineDetails.nextToken();
lastPurDate = lineDetails.nextToken();
maxCredit = Integer.parseInt(lineDetai
currBalance = Integer.parseInt(lineDetai
details[row] = new Customer(id,name,address,p
maxCredit,currBalance);
thisLine = inStream.readLine();
row++;
}
inStream.close();
} catch (IOException e) {
System.out.println("A File I/O error has occured.");
}
}
public Customer[] getDetails() {
if (numberOfRows == 0) {
openMe();
}
return details;
}
public void actionPerformed(ActionEven
if (e.getSource() == disp){
Customer [] getData = getDetails();
String getInput = custID.getText();
Keyword kw = new Keyword(getInput);
Comparator keywordCompare = new KeywordCompare();
int found = Arrays.binarySearch(getDat
if(found>=0){
custName.setText(getData[f
custPh.setText(getData[fou
String maxCredit = new Integer(getData[found].max
String currBalance = new Integer(getData[found].cur
currBal.setText(currBalanc
maxCred.setText(maxCredit)
custAcc.setText(getData[fo
custAddress.setText(getDat
custLastPurchase.setText(g
}
else {
custID.setText("not found");
custName.setText("");
custPh.setText("");
currBal.setText("");
maxCred.setText("");
custAcc.setText("");
custAddress.setText("");
custLastPurchase.setText("
}
}
if (e.getSource() == add){
getDetails();
String [] det ={custID.getText(), custName.getText(), custAddress.getText(),
custPh.getText(), custAcc.getText(), custLastPurchase.getText()
maxCred.getText(), currBal.getText()};
writeTextFile(det);
}
}
public void writeTextFile(String det[]) {
try {
FileWriter outfileWrite = new FileWriter(FileName, true);
BufferedWriter outBufferedWrite = new BufferedWriter(outfileWrit
for(int i=0; i<det.length-1; ++i)
{ outBufferedWrite.write(det
}
outBufferedWrite.write(det
outBufferedWrite.newLine()
outBufferedWrite.close();
} catch (IOException e) {
System.out.println("IOERRO
e.printStackTrace();
}
}
public static void main(String args[]) {
System.out.println("Starti
Monsupp mainFrame = new Monsupp();
mainFrame.setSize(850, 300);
mainFrame.setTitle("Mon_su
mainFrame.setVisible(true)
}
}
Its working except when i add new customer details I cannot redisplay them in the same session I need to somehow re-read the textfile when the display button is pushed. Any Ideas?
Thanks
ASKER
Cheers Javatm appreciate the help
Catcha round
Catcha round
Friend;
>> What I would like to do is be able to use the JFileChooser to select a text file and input that into the String tokenizer
Based on the things that we've already done. I already answered this question.
I gave you 2 things :
1.) A simulation for your actionlistener.
2.) A complete code on how to do it.
>> I need to somehow re-read the textfile ?
This question will be a different question based on the rules of EE. So it should be asked on a different form with
different points.
Anyhow I respect your decision on it :)
Hope it helps . . .
Javatm
>> What I would like to do is be able to use the JFileChooser to select a text file and input that into the String tokenizer
Based on the things that we've already done. I already answered this question.
I gave you 2 things :
1.) A simulation for your actionlistener.
2.) A complete code on how to do it.
>> I need to somehow re-read the textfile ?
This question will be a different question based on the rules of EE. So it should be asked on a different form with
different points.
Anyhow I respect your decision on it :)
Hope it helps . . .
Javatm
Still there friend :)