I wondered if anyone could help. I am trying to use a FileChooser in java. I have got the dialog box to appear and can select the file, but the box just displays "opening" and the file name. how to I add to the code to make it actually open the text file?
here is my current code:
package org.work;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
public class FileChooser extends JFrame
{
private JTextArea log;
private JFileChooser fc = new JFileChooser();
private String newline = System.getProperty("line.separator");
public FileChooser()
{
super("FileChooserDemo");
JButton openButton = new JButton("Open", new ImageIcon("images/open.gif")); //Create the open button and add image
openButton.addActionListener(new OpenListener()); //Adds action listener to the open button
JButton saveButton = new JButton("Save", new ImageIcon("images/save.gif")); //Create the save button and add image
saveButton.addActionListener(new SaveListener()); //Adds action listener to the save button
JPanel buttonPanel = new JPanel(); //Create a panel
buttonPanel.add(openButton); //Add the open button to the panel
buttonPanel.add(saveButton); //Add the save button to the panel
log = new JTextArea(5,20); //Create the text area
log.setMargin(new Insets(5,5,5,5)); //Set the margins
JScrollPane logScrollPane = new JScrollPane(log);
Container contentPane = getContentPane();
contentPane.add(buttonPanel, BorderLayout.NORTH); //Add the buttons to the panel
contentPane.add(logScrollPane, BorderLayout.CENTER); //Add the text area to the panel
}
private class OpenListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int returnVal = fc.showOpenDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
log.append("Opening: " + file.getName() + "." + newline); //Display "Opening" and the retrieved file name in the text area
} else //If not;
{
log.append("Open command cancelled by user." + newline); //Display this command in the text area
}
}
}
private class SaveListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int returnVal = fc.showSaveDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
log.append("Saving: " + file.getName() + "." + newline); //Display "Saving" and the retrieved file name in the text area
} else //If not;
{
log.append("Save command cancelled by user." + newline); //Display this command in the text area
}
}
}
public static void main(String s[])
{
JFrame frame = new FileChooser();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {System.exit(0);} //Terminates program
});
frame.pack();
frame.setVisible(true); //Set frame to visible
}
}