Hey guys I am running into an issue with my program. I am trying to get the program to only show text files, and once the user selects one, the file information should be displayed in a textbox in the GUI. I am getting this error:
FileChooserDemo3.java:66: error: unreported exception IOException; must be caught or declared to be thrown
while ((strLine = br.readLine()) != null) {
Why is this happening? I have a catch statement.. Thanks for any help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
import java.io.*;
class FileChooserDemo3{
JLabel jlab;
JButton jbtnShow;
JFileChooser jfc;
JTextArea jta;
JScrollPane scrollPane;
FileChooserDemo3() {
//create new JFrame container.
JFrame jfrm = new JFrame("JFileChooser Demo");
//Specify FlowLayout for layout manager
jfrm.setLayout(new FlowLayout());
//Give the frame initial size
jfrm.setSize(800,800);
//End program when user closes application
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a label to show selected file
jlab=new JLabel();
//Create button to show dialog
jbtnShow = new JButton("Show File Chooser");
//create textarea with ability to textwrap (p889-891) and scroll (hint: Use JScrollPane)
JTextArea textInput = new JTextArea(20, 40);
textInput.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textInput);
//Create file chooser starting at default directory
jfc=new JFileChooser();
//Show file chooser when show file chooser button pressed
jbtnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
//Pass null for the parent. This centers the dialog on the screen.
int result = jfc.showOpenDialog(null);
if(result==JFileChooser.APPROVE_OPTION){
jlab.setText("Selected file is: " + jfc.getSelectedFile().getName());
//Get selected file stored as a file.
try{
//Do file processing here
String strLine;
File selectedFile = jfc.getSelectedFile();
FileInputStream in = new FileInputStream(selectedFile);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
textInput.append(strLine + "\n");
}
}
catch(FileNotFoundException e){
System.out.println("Exception");
}
}
else{
jlab.setText("No file selected.");
}
}
});
//add the show file chooser button and label to content pane
jfrm.add(jbtnShow);
jfrm.add(jlab);
//Display the frame
jfrm.setVisible(true);
}
public static void main(String[] args){
//Create GUI on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FileChooserDemo3();
}
});
}
}
You are catching FileNotFoundException, but you also need to catch IOException after your try {} block.
Programmatically, this is because readLine declares throws IOException. Translated, what it's saying is that even after the file is opened, it could still encounter a problem reading from the file.
Whats happening is exactly what it says is happening. "unreported exception IOException." Basically your catch statement is not catching all possible exceptions that can be thrown, change it to catch either IOException, or to make sure it catches every possible excepion, no matter what, make it catch Exception.
Related
Need to display selected in FileDialog image, but thats somewhy didnt work. When i try to choose image it throws exception javax.imageio.IIOException: Can't create an ImageInputStream!
I think problem is in getDirectory() , but dont know how to fix.
public ImageShow() throws IOException {
super("Pictures");
setSize(1024,768);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonOpen = new JButton("Open file");
buttonPanel.add(buttonOpen);
actions();
fileDialog();
add(buttonPanel);
image = ImageIO.read(new File(fd.getDirectory()));
imageLabel = new JLabel(new ImageIcon(image));
buttonPanel.add(imageLabel);
}
public void fileDialog() {
fd = new FileDialog(new JFrame(), "Choose file");
fd.setVisible(true);
}
public void actions() {
buttonOpen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fileDialog();
}
});
}
}
image = ImageIO.read(new File(fd.getDirectory()));
A directory is not an image! Try instead getFile() which:
Gets the selected file of this file dialog. If the user selected CANCEL, the returned file is null.
But as I said in comments..
Use the Swing based JFileChooser rather than the AWT based FileDialog.
And be sure to consult the avialable documentation when using methods.
Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
JButton save,help,savePath;
//JTextArea text;
public EventListeners(){
window();
}
public void window(){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(650,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10,50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500,500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20,100);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
}
});
}
public static void main(String[] args) {
new EventListeners();
}
}
main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.
for example
you have declare instance variable
JButton save, help, savePath, saveFilePath;
inside constructor you are creating another local jbutton and initialize it so instance variable is null.
so instead of creating new one you should initialize instance field.
JButton saveFilePath = new JButton("File Path Save Settings"); // problem
saveFilePath = new JButton("File Path Save Settings"); // correct way
but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.
also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.
also you should call repaint() at last after you add all the component to a frame..
try to run this code
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName, filePathSaveDirectory, savedFilePath;
JButton save, help, savePath, saveFilePath;
//JTextArea text;
public EventListeners() {
window();
}
public void window() {
JFrame window = new JFrame();
window.setSize(650, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10, 50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500, 500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
System.out.println(savePath);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
}
});
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20, 100);
window.setVisible(true);
}
public static void main(String[] args) {
new EventListeners();
}
}
You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like
public EventListeners(JButton save, JButton help, JButton saveFilePath) {
this.save = save;
this.help = help;
this.saveFilePath = saveFilePath);
}
Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.
I do not want to specify a directory. I just want it to automatically "know" and open in the directory the user is working in. How do I do this?
This examples defaults to the user.dir on first showing. It then retains the instance of the chooser to automatically track the last load or save location, as suggested by MadProgrammer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
public class ChooserInCurrentDir {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
JFileChooser fileChooser;
private JTextArea output = new JTextArea(10, 40);
ChooserInCurrentDir() {
initComponents();
}
public final void initComponents() {
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
String userDirLocation = System.getProperty("user.dir");
File userDir = new File(userDirLocation);
// default to user directory
fileChooser = new JFileChooser(userDir);
Action open = new AbstractAction("Open") {
#Override
public void actionPerformed(ActionEvent e) {
int result = fileChooser.showOpenDialog(gui);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File f = fileChooser.getSelectedFile();
FileReader fr = new FileReader(f);
output.read(fr, f);
fr.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};
Action save = new AbstractAction("Save") {
#Override
public void actionPerformed(ActionEvent e) {
int result = fileChooser.showSaveDialog(gui);
throw new UnsupportedOperationException("Not supported yet.");
}
};
JToolBar tb = new JToolBar();
gui.add(tb, BorderLayout.PAGE_START);
tb.add(open);
tb.add(save);
output.setWrapStyleWord(true);
output.setLineWrap(true);
gui.add(new JScrollPane(
output,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
}
public final JComponent getGui() {
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ChooserInCurrentDir cicd = new ChooserInCurrentDir();
JFrame f = new JFrame("Chooser In Current Dir");
f.add(cicd.getGui());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Basically, you can't. You need to tell it.
When constructed with a null currentDirectory (such as the default constructor), it will use FileSystemView#getDefaultDirectory.
You could create a single instance of JFileChooser for each base task (one for saving, one for opening for example) and simply maintain that instance, which will "remember" the last directory that it was using, you'd still need to seed it with a starting directory though
Another choice would be to construct some kind of library call that could load and save the last directory the user used based on some unique key. This means you could simply do something like...
File toFile = MyAwesomeLibrary.getSaveFile(APPLICATION_DOCUMENT_SAVE_KEY);
Which would load the last known directory for the supplied key and show the JFileChooser configured with that value and would be capable of returning the selected File or null if the user canceled the operation...for example...
If you want to set the directory they were in at the previous opening of the file chooser you need to set the current directory.
//This will set the directory to the directory they previously chose a file from.
fileChooser.setCurrentDirectory(fileChooser.getCurrentDirectory());
Im not sure if this is what you're looking for, But when they select a file then go to select another file, it will maintain the directory they were in from the previous selection.
If you want your application to look for the user's working directory, you can try this:
String curDir = System.getProperty("user.dir");
How do you display the contents of a text file in a TextArea when your using JFileChooser.
You have to read official Oracle's JTextArea tutorial
Especially method JTextArea.read(fileSelectedFromJFileChooser) , maybe right way in this case
Please have a look at Reading, Writing and Creating Files Tutorials
Here find one example program, for your help, though if the file to be read is long, then always take the help of SwingWorker :
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReadFileExample
{
private BufferedReader input;
private String line;
private JFileChooser fc;
public ReadFileExample()
{
line = new String();
fc = new JFileChooser();
}
private void displayGUI()
{
final JFrame frame = new JFrame("Read File Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextArea tarea = new JTextArea(10, 10);
JButton readButton = new JButton("OPEN FILE");
readButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
try
{
input = new BufferedReader(
new InputStreamReader(
new FileInputStream(
file)));
tarea.read(input, "READING FILE :-)");
}
catch(Exception e)
{
e.printStackTrace();
}
} else {
System.out.println("Operation is CANCELLED :(");
}
}
});
frame.getContentPane().add(tarea, BorderLayout.CENTER);
frame.getContentPane().add(readButton, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ReadFileExample().displayGUI();
}
});
}
}
Your question is unclear, but I am assuming you want to add the JTextArea to the JFileChooser so that it can act like a file preview panel.
You can add a JTextArea to the JFileChooser by using the setAccessory() method.
This tutorial on JFileChooser shows how to do something similar where the accessory displays an image from the file rather than text from the file.
You will need to be careful to deal properly with files that don't contain text, or which are too large, or which cannot be opened due to permission, etc. It will take a good bit of effort to get it right.
Alright... I'm starting out with Java and I've stepped up to Swing GUI. Everything was going fine until I tried to work with file input and output.
/*
** 'Gooey' GUI in Swing with Java.
** v3 With File Opening
*/
import javax.swing.*; // Import the swing library
import javax.swing.filechooser.*;
import java.awt.*; // Import library
import java.awt.event.*; // Import event handling
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
class gooey implements ActionListener {
JFrame myFrame = null; // Create a JFrame, don't fill it
JEditorPane myPane = null;
String fileName = "myJava.java";
Font editorFont = new Font("Consolas",Font.PLAIN, 12);
public static void main(String[] args) {
(new gooey()).test(); // Create a GUI and 'test' it
}
private void test() { // Test run of a gooey
// FRAME
//////////
System.out.println("Creating myFrame..."); // Debug stuff
myFrame = new JFrame("Gooey"); // Create a new JFrame (window)
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Set it so that when the [X] button is clicked, the app exits
myFrame.setSize(400,300); // Set the size of 400x300px (WxH)
System.out.println("myFrame created!"); // Debug stuff
// MENU BAR
/////////////
System.out.println("Creating menuBar..."); // Debug stuff
JMenuBar myBar = new JMenuBar(); // Create a new JMenuBar called myBar
System.out.println("Done!"); // More debug stuff
System.out.println("Creating JButtons...");
JButton openButton = new JButton("Open"); // Create a button named openButton
openButton.addActionListener(this);
JButton saveButton = new JButton("Save"); // Create a button named saveButton
saveButton.addActionListener(this);
JButton quitButton = new JButton("Quit"); // Create a button named quitButton
quitButton.addActionListener(this); // Add an actionListener
myBar.add(openButton); // Add the buttons to the menubar
myBar.add(saveButton);
myBar.add(quitButton);
System.out.println("Done!"); // Even more debug stuff
// EDITOR PANE
////////////////
System.out.println("Creating myPane..."); // EVEN MOAR DEBUG
JEditorPane myPane = new JEditorPane(); // Create a new JEditorPane called myPane
myPane.setContentType("text/plain"); // Set it so that it can only edit plain text
myPane.setFont(editorFont);
myPane.setText(
"This is a JEditorPane."
+"\nIt can display text/rich text/HTML that can be edited."); // Set the starting text of myPane to that
System.out.println("Done!"); // And yet more debug stuff
// RUNNING IT
///////////////
System.out.println("Running it all..."); // DEBUG
myFrame.setJMenuBar(myBar); // Set the frame's menu bar to myBar
myFrame.setContentPane(myPane); // Set it so that the content in myFrame is myPane
myFrame.setVisible(true); // Make myFrame visible
System.out.println("myFrame has been created!");
}
// ACTION LISTENERS
/////////////////////
public void actionPerformed(ActionEvent e) {
// Basically, every time an action is performed (e.g. left mouse click)
// on something with an actionListener attached to it, we can call this
// method.
if (e.getActionCommand()=="Quit") System.exit(0); // If the string of the thing we're listening to was "quit", exit the program!
else {
// CREATE A FILE CHOOSER
/////////////////////////
JFileChooser myFileChoose = new JFileChooser();
myFileChoose.setCurrentDirectory(new File("C:"));
myFileChoose.setSelectedFile(new File(fileName));
myFileChoose.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter myFilter = new FileNameExtensionFilter(".java files","java");
myFileChoose.setFileFilter(myFilter);
try {
// OPEN COMMAND
/////////////////
if (e.getActionCommand()=="Open") {
int r = myFileChoose.showOpenDialog(myPane); // Create a file chooser
if (r == JFileChooser.APPROVE_OPTION) { // If the user has selected a file
File selectedFile = myFileChoose.getSelectedFile(); // Find that file
fileName = selectedFile.getName(); // Get it's name and store it in a variable
FileInputStream fis = new FileInputStream(selectedFile); // Stream the input
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); // Read said stream
char[] buffer = new char[1024]; // Create a buffer
int n = isr.read(buffer); // Read from the input and buffer
String text = new String(buffer, 0, n); // Put into string
myPane.setText(text); // Put into JEditorPane
isr.close();
}
// SAVE COMMAND
/////////////////
} else if (e.getActionCommand()=="Save") {
int r = myFileChoose.showOpenDialog(myPane);
if (r == JFileChooser.APPROVE_OPTION) { // If the user has selected a file
File selectedFile = myFileChoose.getSelectedFile(); // Find that file
fileName = selectedFile.getName(); // Get it's name and store it in a variable
FileOutputStream fos = new FileOutputStream(selectedFile); // Stream the input
OutputStreamWriter osr = new OutputStreamWriter(fos, Charset.forName("UTF-8")); // Read said stream
osr.write(myPane.getText());
osr.close();
}
}
} catch (Exception q) {
q.printStackTrace();
}
}
}
}
I try to make it work, however when I try to open or save a file via a JFileChooser, it shows me these:
Open file error:
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:120)
Save file error:
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:132)
The variable myPane is not initialized (null). This causes the NullPointerException.
You create a new JEditorPane (around line 65) but assign it to a local variable, so the class member with the same name is still null (and actionPerformed uses the class member variable myPane). Change line 65
JEditorPane myPane = new JEditorPane();
to
myPane = new JEditorPane();