How to Display the Contents of a text file in a TextArea - java

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.

Related

Java Null Pointer When clicking JButton(Eclipse)

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.

Processing a file with JFileChooser

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.

How do I make JFileChooser open in the current directory the user is in?

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");

Use value of a variable from another class

I have this jFrame class:
public class Frame1 extends javax.swing.JFrame {
........
String name;
File file;
JFileChooser FileChooser = new JFileChooser();
if (FileChooser.getSelectedFile().isFile()) {
try {
file = FileChooser.getSelectedFile();
name = FileChooser.getSelectedFile().getName();
System.out.println( name );
} catch (FileNotFoundException ex) {
Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, ex);
}
}
........
private void Button1 (java.awt.event.ActionEvent evt) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Frame2 obj = new Frame2 ();
}
});
}
}
Then I created the class "Frame2":
public class Frame2 extends javax.swing.JFrame {
.......
}
As you can image, when my program starts I use a JFileChooser to choose a file;
after that I click a button that opens another jFrame; in this jFrame (Frame2)
What I would need is to use the file that I have chosen in the previous jFrame (Frame1).
So I need to use "file" variable from "Frame1" in "Frame2".
I tried to do this in Frame2:
Frame1 obj1 = new Frame1();
File file2 = obj1.file;
System.out.println( file2 );
So when I run the program and choose a file and then I click "Button1" to run "Frame2", it first prints the file name ("name") from "Frame1"
and after that it prints "null" so I can't get correct "file" value from "Frame1" and use it in "Frame2".
How can I do that?
Thanks
This won't work:
Frame1 obj1 = new Frame1();
File file2 = obj1.file;
System.out.println( file2 );
because it falls into a common newbie trap: thinking that a new instance of a class (here Frame1) holds the same information as another previously used instance of the class (the previous Frame1 instance that was displayed), and this simply isn't true unless you use static variables -- something I strongly urge you not to do.
Instead why not:
Change your first JFrame into a modal JDialog or JOptionPane
Give it a public method getSelectedFile() that returns the selected file. This is what your question is really about -- sharing the state of one object with another object -- and one way to do this is via your basic getter and setter methods.
Then show your dialog, and when it returns, call the above method on the above object.
Or why not instead simply show a JFileChooser dialog since it does all of this for you?
For example:
import java.io.File;
import javax.swing.*;
public class Foo {
private static void createAndShowGui() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
JTextField field = new JTextField(file.getAbsolutePath(), 30);
JPanel panel = new JPanel();
panel.add(new JLabel("Selected File:"));
panel.add(field);
// create and open a new JFrame with the selected file's path
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How do i write to a text file using java?

I have been using the "Learning Java 2nd Edtion" book to try make my java application write my input to a text file called properties. I have manipulated the text book example into my own code but still having problems trying to get it to work. I think i may need to hook it up to my submit button but this wasnt mentioned within the chapter.
Basically im trying to store the information in the text file and then use that text file within another location to read all of the property details.
Here is my code for the AddProperty Page so far any advice would be greatly appreciated.
At the moment iv hit the wall.
/**
*
* #author Graeme
*/
package Login;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class AddProperty
{
public void AddProperty()
{
JFrame frame = new JFrame("AddPropertyFrame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// having to set sizes of components is rare, and often a sign
// of problems with layouts.
//frame.setSize(800,600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
// make it big like the original
panel.setBorder(new EmptyBorder(100,20,100,20));
frame.add(panel);
//panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JLabel HouseNumber = new JLabel("House Number/Name");
panel.add(HouseNumber);
JTextField HouseNumber1 = new JTextField(10);
panel.add(HouseNumber1);
JLabel HousePrice = new JLabel("House Price");
panel.add(HousePrice);
JTextField HousePrice1 = new JTextField(10);
panel.add(HousePrice1);
JLabel HouseType = new JLabel("House Type");
panel.add(HouseType);
JTextField HouseType1 = new JTextField(10);
panel.add(HouseType1);
JLabel Location = new JLabel("Location");
panel.add(Location);
JTextField Location1 = new JTextField(10);
panel.add(Location1);
JButton submit = new JButton("Submit");
panel.add(submit);
submit.addActionListener(new Action());
// tell the GUI to assume its natural (minimum) size.
frame.pack();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e)
{
// this should probably be a modal JDialog or JOptionPane.
JOptionPane.showMessageDialog(null, "You have successfully submitted a property.");
}
static class propertyList
{
public static void main (String args[]) throws Exception {
File properties = new File(args[0]);
if (!properties.exists() || !properties.canRead() ) {
System.out.println("Cant read " + properties);
return;
}
if (properties.isDirectory()){
String [] properties1 = properties.list();
for (int i=0; i< properties1.length; i++)
System.out.println();
}
else
try {
FileReader fr = new FileReader (properties);
BufferedReader in = new BufferedReader (fr);
String line;
while ((line = in.readLine())!= null)
System.out.println(line);
}
catch (FileNotFoundException e){
System.out.println("Not Able To Find File");
}
}
}
}
}
in your Action performed you are not stating anything, for example in your action performed you could add.
public void actionPerformed(ActionEvent e)
{
houseNumber2 = houseNumber1.getText();
housePrice2 = housePrice1.getText();
town1 = town.getText();
comboBoxType2 = comboBoxType1.getSelectedItem();
inputData = housenumber2 + "," + housePrice2 + "," + town1 + "," + comboBoxType2;
FileName.Filewritermethod(inputData);
frame.setVisible(false);
}
});
This would strings to take the values of your JTexFields and pass them onto a textfile provided you have a FileWriter Class
Your action listener is not doing anything much right now.
Add code to add property in the following method:
public void actionPerformed (ActionEvent e)
{
//add your code here
}

Categories