following this question, error message with JButton and JFileChooser, I want to have a JButton to browse a file using JFileChooser. This is the code we have:
package main;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
private static Component frame;
private static String fullPath;
public static void main(String args[]) throws FileNotFoundException, IOException {
Date start_time = new Date();
try {
GridBagConstraints gbc = new GridBagConstraints();
JButton inputButton = new JButton("Browse input file");
final JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
JPanel myPanel = new JPanel(new GridBagLayout());
myPanel.add(inputButton, gbc);
inputButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file1 = inputFile.getSelectedFile();
String fullpathTemp = (String) file1.getAbsolutePath();
fullpathTemp = fullPath;
}
}
});
Date stop_time = new Date();
double etime = (stop_time.getTime() - start_time.getTime()) / 1000.;
System.out.println("\nElapsed Time = " + etime + " seconds\n");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
}
}
}
The problem is that after clicking on button "Browse the input file" and choose the file, as soon as I click on OK, I get this error message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Main$1.actionPerformed(Main.java:195)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
You've declared inputFile 3 times
Once as a static class variable
private static JFileChooser inputFile;
Then in you're main method
final JFileChooser inputFile = new JFileChooser();
// this can't possible compile
inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
And then in your ActionListener
inputButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file1 = inputFile.getSelectedFile();
String fullpathTemp = (String) file1.getAbsolutePath();
fullpathTemp = fullPath;
}
}
});
It should be possible for any of these to interfere with each other that would produce your NullPointerException that I can see, but given the fact that your code example won't actually compile I can only imagine we're not seeing everything
Related
I am creating a user interface for a pdf reader, and I want to have a list with recent open files. (Not the content of the files, just the name of the file).
From the snap shared, I assume that you are using JFileChooser for your dialog to open file. Hope this helps!
int result = fileChooser.showOpenDialog(panel);
//where panel is an instance of a Component such as JFrame, JDialog or JPanelwhich is parent of the dialog.
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
textArea.setText(selectedFile.getName());
}
The example below uses a JFileChooser with setMultiSelectionEnabled(true) to add() one or more files to a List<File> and update() a JTextArea with the current list. As suggested here, you can use Action to maintain a menu or tool bar of recent files.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
* #see https://stackoverflow.com/a/37153404/230513
* #see https://stackoverflow.com/a/4039359/230513
*/
public class Test {
private final List<File> recentFiles = new ArrayList<>();
private final JTextArea textArea = new JTextArea(12, 12);
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setBorder(BorderFactory.createTitledBorder("Recent Files"));
f.add(textArea);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Open") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(".");
jfc.setMultiSelectionEnabled(true);
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
recentFiles.addAll(Arrays.asList(jfc.getSelectedFiles()));
update();
}
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private void update() {
textArea.setText("");
for (File file : recentFiles) {
textArea.append(file.getName() + "\n");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
I'm trying to set up face detection with JavaCV. I've got working code with cvLoadImage but when I try to load an image via Highgui.imread there's an error: 'Highgui cannot be resolved' and 'Highgui' has red wavy underlining. For some reason Eclipse cannot deal properly with imported com.googlecode.javacv.cpp.opencv_highgui or ...?
Problem here:
CvMat myImg = Highgui.imread(myFileName);
Full code:
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
import com.googlecode.javacv.cpp.opencv_core.CvRect;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSeq;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_objdetect.CvHaarClassifierCascade;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import java.awt.Button;
import java.io.File;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMat;
import com.googlecode.javacv.cpp.opencv_highgui;
//import opencv_highgui;
public class Form1 {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
String myFileName = "";
//Load haar classifier XML file
public static final String XML_FILE =
"resources/!--master--haarcascade_frontalface_alt_tree.xml";
private JFrame frame;
//Detect for face using classifier XML file
public static void detect(IplImage src){
//Define classifier
CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(cvLoad(XML_FILE));
CvMemStorage storage = CvMemStorage.create();
//Detect objects
CvSeq sign = cvHaarDetectObjects(
src,
cascade,
storage,
1.1,
3,
0);
cvClearMemStorage(storage);
int total_Faces = sign.total();
//Draw rectangles around detected objects
for(int i = 0; i < total_Faces; i++){
CvRect r = new CvRect(cvGetSeqElem(sign, i));
cvRectangle (
src,
cvPoint(r.x(), r.y()),
cvPoint(r.width() + r.x(), r.height() + r.y()),
CvScalar.RED,
2,
CV_AA,
0);
}
//Display result
cvShowImage("Result", src);
cvWaitKey(0);
}
/**
* Create the application.
*/
public Form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
JLabel Label1 = new JLabel(" ");
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 301, 222);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnDetect = new JButton("Detect");
btnDetect.setVerticalAlignment(SwingConstants.TOP);
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//IplImage img = cvLoadImage("resources/lena.jpg");
IplImage img = cvLoadImage(myFileName);
CvMat myImg = Highgui.imread(myFileName);
detect(img);
}
});
frame.getContentPane().add(btnDetect, BorderLayout.SOUTH);
Label1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Label1, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Open");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Открыть файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
myFileName = file.getAbsolutePath();
Label1.setText(myFileName);
}
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 window = new Form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//Load image
//IplImage img = cvLoadImage("resources/lena.jpg");
//detect(img);
}
}
External JARs: http://pasteboard.co/jwqNHC9.png
Full project in ZIP
I've also followed all steps from here: http://opencvlover.blogspot.in/2012/04/javacv-setup-with-eclipse-on-windows-7.html
Any help will be appreciated.
Mat m = Highgui.imread(myFileName); is from the builtin opencv java wrappers , not from javacv ( which is a independant, 3rd party wrapper ).
unfortunately, both concurrent apis are pretty incompatible, as javacv is wrapping the outdated c-api, and the opencv ones are wrapping the more modern c++ api.
I tried to write a simple test program using Swing, all I want to do is load a text file and display the path of the chosen text file in a text area. I keep getting a warning on the process method "never used locally" and it is not appending any text to the textbox. Maybe I'm misunderstanding something, I hope someone can help me.
code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MyPanel3 extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea jcomp;
private JButton btn;
private String testfile;
public MyPanel3() {
//construct components
jcomp = new JTextArea (1, 1);
jcomp.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
btn = new JButton ("open");
//adjust size and set layout
setPreferredSize (new Dimension (944, 575));
BoxLayout layout = new BoxLayout (this, BoxLayout.Y_AXIS);
setLayout(layout);
//add main components
add (jcomp);
add (btn);
new SwingWorker<Void, String>(){
protected Void doInBackground(){
//do processes...
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JFileChooser chooseFile = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt","txt");
chooseFile.setFileFilter(filter);
chooseFile.setAcceptAllFileFilterUsed(false);
chooseFile.setMultiSelectionEnabled(true);
if(ae.getSource().equals(btn))
{
System.out.println("do in background running");
int returnVal = chooseFile.showOpenDialog(MyPanel3.this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File[] files = chooseFile.getSelectedFiles();
testfile = files[0].getPath();
publish(testfile);
}
}
}
});
return null;
}
protected void process(String s) {
jcomp.append(s);
}
protected void done() {
try
{
//System.out.println("The operation was completed");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.execute();
}
public static void main(String[] args){
JFrame frame = new JFrame ("MyTest");
frame.getContentPane();
frame.add(new MyPanel3());
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible (true);
}
}
warning reads:
The method process(String) from the type new
SwingWorker(){} is never used locally
EDIT:
with help from MadProgrammer, program is now working (selecting 3 files and printing the paths as strings in the text box)
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MyPanel4 extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea jcomp;
private JButton btn;
public MyPanel4() {
//construct components
jcomp = new JTextArea(1, 1);
jcomp.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
btn = new JButton("open");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JFileChooser chooseFile = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "txt");
chooseFile.setFileFilter(filter);
chooseFile.setAcceptAllFileFilterUsed(false);
chooseFile.setMultiSelectionEnabled(true);
int returnVal = chooseFile.showOpenDialog(MyPanel4.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File[] files = chooseFile.getSelectedFiles();
new SwingWorker<Void, String>() {
private String testfile1 = files[0].getPath();
private String testfile2 = files[1].getPath();
private String testfile3 = files[2].getPath();
protected Void doInBackground() {
List<String> b = new ArrayList<String>();
b.add(testfile1);
b.add(testfile2);
b.add(testfile3);
publish(b.get(0));
publish(b.get(1));
publish(b.get(2));
return null;
}
#Override
protected void process(List<String> chunks) {
for (String pathname : chunks)
{
jcomp.append(pathname + "\n");
}
}
protected void done() {
try
{
System.out.println("Opration Completed");
} catch (Exception e) {
e.printStackTrace();
}
}
}.execute();
}
}
});
//adjust size and set layout
setPreferredSize(new Dimension(944, 575));
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(layout);
//add main components
add(jcomp);
add(btn);
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyTest");
frame.getContentPane();
frame.add(new MyPanel4());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
The SwingWorker should be created inside the buttons actionPerformed method, so that when you click the button, it will run the SwingWorker
You should, also, make sure that all interactions with user interface are fine from within the context of the Event Dispatching Thread. This means you should ask the user to select the file fro within the context of the actionPerformed method and pass the result to the SwingWorked
Updated
Two additional things...
You're not actually reading the file, but simply passing the name of the file to the publish method
SwingWorker defines process as protected void process(List<V> chunks) but you've defined it as protected void process(String s)...mean that you are actually not overriding the SwingWorker's process method, but creating your own...
Take a look at this example to see how you might be able to use a SwingWorker to read a file...
And, update your process to have the corrected method signature...
#Override
protected void process(List<String> chunks) {
for (String line : chunks) {
output.append(line);
}
}
Remember, you should, as much as possible, use the #Override annotation when you think you are overriding a method, the compiler will tell you when you are mistaken, saving you a lot of head scratching...
It should be like this:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MyPanel3 extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea jcomp;
private JButton btn;
private String testfile;
public MyPanel3() {
//construct components
jcomp = new JTextArea(1, 1);
jcomp.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
btn = new JButton("open");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JFileChooser chooseFile = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "txt");
chooseFile.setFileFilter(filter);
chooseFile.setAcceptAllFileFilterUsed(false);
chooseFile.setMultiSelectionEnabled(true);
int returnVal = chooseFile.showOpenDialog(MyPanel3.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File[] files = chooseFile.getSelectedFiles();
testfile = files[0].getPath();
new SwingWorker<Void, String>() {
protected Void doInBackground() {
publish(testfile);
return null;
}
protected void process(String s) {
jcomp.append(s);
}
protected void done() {
try {
//System.out.println("The operation was completed");
} catch (Exception e) {
e.printStackTrace();
}
}
}.execute();
}
}
});
//adjust size and set layout
setPreferredSize(new Dimension(944, 575));
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(layout);
//add main components
add(jcomp);
add(btn);
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyTest");
frame.getContentPane();
frame.add(new MyPanel3());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
You are running worker when you are creating panel. But you should run it when button is clicked.
Ok so I have a text editor made that can so far create new files and open files using jFileChooser.
What I am trying to do is get the saving of files to work.
Everytime you add or open a few file it adds a new tab to the tabbedpane and the name will be either file 1 etc or the name of the file opened.
When you click the save button the save dialog opens up
int returnVal = fileChooser.showSaveDialog(this);
I want the name on the tab to be inserted to the name of file field.
Also how do I make a file of the current selected tabs textarea? I have tried this but its a no go:
int index = tabbedPane.getSelectedIndex();
Component c = tabbedPane.getComponentAt(index);
JTextArea a = (JTextArea) c;
System.out.println(a.getText());
File file = new File(a.getText());
fileChooser.setSelectedFile(file);
So I need to make a file of the string in the textArea I guess.
Following up #Andrew's answer, here is a snippet illustrating what he meant. I took the liberty to rather use a OutputStreamWriter than a FileWriter because this allows you to choose the charset used to write the file, which is something that you usually want to control and not rely on the "random" default platform charset.
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TestTextArea {
private JTextArea textArea;
private JButton save;
protected void initUI() {
JFrame frame = new JFrame(TestTextArea.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea(24, 80);
save = new JButton("Save to file");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveToFile();
}
});
frame.add(new JScrollPane(textArea));
JPanel buttonPanel = new JPanel();
buttonPanel.add(save);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(500, 400);
frame.setVisible(true);
}
protected void saveToFile() {
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(save);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".txt")) {
file = new File(file.getParentFile(), file.getName() + ".txt");
}
try {
textArea.write(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Desktop.getDesktop().open(file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTextArea().initUI();
}
});
}
}
An easy way is to use JTextComponent.write(Writer). JTextArea extends JTextComponent.
For the Writer use a FileWriter.
You need to, some how associate the File that was opened with the tab. That way, you can look up the File associated based on the selected tab.
Something like HashMap<Component, File> for example
I faced a problem that the typed data can not be persistent. I want to store java Swing GUI to XML file and reuse them latter. Now I store the GUI successfully. But after I type some data into the textfield. The typed data can not be encoded into XML file. Could you help me store both the GUI and the typed content? Below is the code using javabeans XMLencoder:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.beans.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ResourceName extends JFrame implements ActionListener{
static JFileChooser chooser;
JButton save,load;
JTextField tf;
static JFrame frame;
public ResourceName(){
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
frame = new JFrame("ResourceName");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
save = new JButton("Save");
save.setActionCommand("Save");
save.addActionListener(this);
load = new JButton("Load");
load.setActionCommand("Load");
load.addActionListener(this);
tf = new JTextField(10);
frame.add(save);
frame.add(tf);
frame.add(load);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if((e.getActionCommand()).equals("Save"))
{
save();
}else if((e.getActionCommand()).equals("Load"))
{
load();
}
}
public void save()
{
if(chooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
try{
File file = chooser.getSelectedFile();
XMLEncoder encoder = new XMLEncoder(new FileOutputStream(file));
encoder.writeObject(frame);
encoder.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
public void load()
{
//show file chooser dialog
int r = chooser.showOpenDialog(null);
// if file selected, open
if(r == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
XMLDecoder decoder = new XMLDecoder(new FileInputStream(file));
decoder.readObject();
decoder.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
public static void main(String[] args) {
ResourceName test = new ResourceName();
}
}
Please help me solve this problem. Many Thanks!
it may be that the text property, is transient, this means it won't be saved to the output automatically, by an ObjectOutputStream. You'll probably have to explicitly write that field.