Reading text from file and putting it to the JLabel - java

I want to change my JLabel when I click a JButton. It sounds simple but can't really find a good piece of code.
Here is part of my code:
final JButton continueGame = new JButton();
continueGame.setPreferredSize(new Dimension(1000, 30));
continueGame.setLocation(95, 45);
continueGame.setText("<html>Continue</html>");
continueGame.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev) {
panel.remove(continueGame);
SwingUtilities.updateComponentTreeUI(frameKontrastGame);
if(RandomNrJeden <= 50)
{
JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be green.");
frameKontrastGame.setVisible(false);
JFrame frameScenario2 = new JFrame();
frameScenario2.setTitle("Scenario2");
frameScenario2.setSize(1000,700);
frameScenario2.setLocationRelativeTo(null);
frameScenario2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelScenario = new JPanel ();
panel.setLayout(new GridLayout(2, 1));
final JLabel tekst = new JLabel ();
tekst.setText("<html>Część dialogu numer 1</html>");
//JTextField dialog = new JTextField(20);
//dialog.setText("<html>Eggs are not supposed to be green.</html>");
JButton OdpPierwsza = new JButton ();
OdpPierwsza.setText("<html>Opowiedź pierwsza</html>");
OdpPierwsza.addActionListener (new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev) {
tekst.setText("<html>HERE I NEED A TEXT FROM FILE dialog.txt</html>");
}
});
//panelScenario.add(dialog);
panelScenario.add(tekst);
panelScenario.add(OdpPierwsza);
frameScenario2.getContentPane().add(panelScenario);
frameScenario2.setVisible(true);
}
(If the brackets are wrong that's because its not the whole code.)
So:
Where is the "HERE I NEED A TEXT FROM FILE dialog.txt" I need some kind of reader. The best one will be the one which reads text line by line. I just cant find how to write it.
I need to add the JLabel to the JPanel.

You can read your file into just one string using
BufferedReader br = new BufferedReader(new FileReader("your_file.txt"));
String line = br.readLine();
ArrayList<String> listOfStrings = new ArrayList<>();
listOfString.add(line);
while(line != null)
{
line = br.readLine();
listOfString.add(line);
}
And now do a for-loop to iterate over the JList and add text to the JLabel. Better is a JTextArea.

Related

ActionListener nested within an ActionListener? [duplicate]

This question already has answers here:
Detect enter press in JTextField
(10 answers)
Closed 7 years ago.
I have a program that has three functions; to read a file, write to a file and search for specific text within a file. I'm currently working on creating a GUI to use with it so that I will no-longer rely on the console. I've already created a fully functional "main window" and functional buttons with respect to the three aforementioned functions, as well as an exit button. Now I'm working on the GUI window for my Search function - the window is created as the response to the Search button being clicked. I have the window and components layed out the way I want but I'm having trouble setting up the action listener for when the user presses Enter after inputting the string they wish to search for. I've looked at a number of different sources including SOverflow, the javadoc and actionlistener tutorials; but I'm getting nowhere fast.
Here is the base code to draw the Search button in the main window and link to the Search GUI (I linked to this through main):
public class SimpleDBGUI{
static File targetFile; //Declare File var to be used in methods below for holding user's desired file
static JTextField sdbTarget;
static JTextField searchTerm;
public void mainWindow(){
//Create main window for Program
JFrame mainWindow = new JFrame("Simple Data Base"); //Init frame
mainWindow.setSize(500, 180); //Set frame size
mainWindow.setVisible(true); //Make frame visible
//Create panel for the main window of the GUI
JPanel simpleGUI = new JPanel( new GridBagLayout());
GridBagConstraints gbCons = new GridBagConstraints();
mainWindow.getContentPane().add(simpleGUI); //Adds JPanel container to the ContentPane of the JFrame
//Create button linking to the search function
JButton searchButton = new JButton("Search"); //Init button with text
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 1;
gbCons.gridy = 2;
gbCons.weightx = .1;
searchButton.setActionCommand("Search");
searchButton.addActionListener( new ButtonClickListener());
simpleGUI.add(searchButton, gbCons); //Adds the "Search" button to the JPanel
//Create TextField for user to input a desired file
sdbTarget = new JTextField();
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 0;
gbCons.gridy = 1;
gbCons.gridwidth = 3;
simpleGUI.add(sdbTarget, gbCons); //Adds TextField to GUI
}
public class ButtonClickListener implements ActionListener{ //Sets the EventListener for every function
public void actionPerformed(ActionEvent event){
targetFile = new File(sdbTarget.getText());
String function = event.getActionCommand(); //Reads the ActionCommand into a string for use in performing desired function
if( function.equals("Search")){ //Search Function, draws search window and components
JFrame searchWindow = new JFrame("SimpleDB Search"); //Draw window
searchWindow.setSize(500, 200);
searchWindow.setVisible(true);
JPanel searchGUI = new JPanel( new GridBagLayout()); //Create container and add to window
GridBagConstraints gb1Cons = new GridBagConstraints();
searchWindow.getContentPane().add(searchGUI);
JLabel searchPrompt = new JLabel("Please input the word/phrase you wish to find:"); //Prompt user to specify string to search for
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 0;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchPrompt, gb1Cons); //Add prompt to container
JTextField searchTerm = new JTextField(); //Create JTextField for user input and add to container
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 1;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchTerm, gb1Cons);
searchTerm.addActionListener(this); //Assign ActionListener to JTextField
JTextArea searchResult = new JTextArea(); //Create search output box and add to container
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 2;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchResult, gb1Cons);
public void actionPerformed( ActionEvent event){ //Tried this as one event handler, supposed to execute the following upon the user pressing Enter, failed of course
boolean stringFound = false; //Set flag false
try{
Scanner searchFile = new Scanner(targetFile); //Read file to be searched into a scanner
String searchInput = searchTerm.getText(); //Read term to search for into a string
while( searchFile.hasNextLine()){ //Check that specified file has a next line and:
String searchLine = searchFile.nextLine(); //Read line into string
if( searchLine.contains(searchInput)){ //Check that Line contains searched term and:
stringFound = true; //If line contains term, set flag to true
searchResult.append("**" + searchLine + "**"); //Append line with term to output box
}
}searchFile.close(); //Close scanner
if(!stringFound){
searchResult.append("The term(s) you searched for does not exist in this file"); //Output if line does not contain term
}
}catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
You should try to re-structure your code some
I would not create the GUI within an actionPerformed, create it outside (or make a class for it extend JFrame), and in actionPerformed, just display it setVisible(true).
Even if this suggestion is not your problem, it would probably solve it.
Your current situation is:
Your are adding the actionListener to JTextField searchTerm, the actionListener that your are adding is actually the ButtonClickListener so you already have an actionPerformed method,hence same method!!!
So outcome is:
when you press enter in your searchTerm the ButtonClickListener.actionPerformed will be called and if you try to write "Search" in the textfield you will see something interesting!!
A short code for adding a new actionListener would be
searchTerm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//DO YOUR STUFF
}
});
Just paste this code in your constructor.
Hope it'll help. Remember your searchTerm should be of jtextfield as the code for jtextxarea is bit different.
searchTerm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPerformed(e);
}
});

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.

Choosing between custom JPanel and JTable layout

I'm trying to set up a JPanel which will display lines and text horizontally. It will take a text file, and I'm trying to display the lines and text at the same time given the size of the file. Would it be more appropriate (being relatively new to coding) to use a JTable layout, or make my own layout on a JPanel?
Below is a very basic example on how you could use a JTextPane to display some text from a text file within a JFrame. If you want to do anything more then things like layoutmangers will come into play, but for simple text display this should be suitable:
public class SO{
public static void main(String[] args) throws IOException{
JFrame frame = new JFrame();
JTextPane pane = new JTextPane();
frame.add(pane);
BufferedReader br = new BufferedReader(new FileReader("D:\\Users\\user2777005\\Desktop\\test.txt"));
String everything = "";
try {
StringBuilder sbuild = new StringBuilder();
String line = br.readLine();
while (line != null) {
sbuild.append(line);
sbuild.append('\n');
line = br.readLine();
}
everything = sbuild.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
br.close();
}
pane.setFont(new Font("Segoe Print", Font.BOLD, 12));
pane.setText(everything);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
As shown a JTexPane does also allow for Font changes.
Good luck!

Nested if(e.getActionCommand().equals("")

Can someone tell me if it is possible to nest the
if(e.getActionCommand().equals("some String"){//do it}
For example. . . .
public void actionPerformed(ActionEvent e)
{
theFrame.hide();
if(e.getActionCommand().equals("Button in theFrame"))
{
newFramerz.show();
if (e.getActionCommand().equals("Button in newFramerz"))
{
//do usual stuff
}
}
}
For some reason, my code was not working when I tried to compile it. Then I suspected the line of code which I've written at the topmost part.
Can anyone tell me if it is possible? An explaination would also be great.
EDIT
Here's a sample code of my problem.
public void ATM_MainMenu()
{
//-----------------------------//
MainMenu = new JFrame("Main Menu");
JPanel TextPanel = new JPanel();
JPanel BTPanel = new JPanel();
JPanel FormPanel = new JPanel();
JLabel TextLabel = new JLabel("Choose Transaction");
JButton InquireBalBT = new JButton("Inquire Balance");
InquireBalBT.addActionListener(this);
JButton DepositBT = new JButton("Deposit");
DepositBT.addActionListener(this);
JButton WithdrawBT = new JButton("Withdraw");
WithdrawBT.addActionListener(this);
TextPanel.setBackground(Color.white);
TextPanel.add(TextLabel);
BTPanel.add(TextPanel);
BTPanel.add(InquireBalBT);
BTPanel.add(DepositBT);
BTPanel.add(WithdrawBT);
FormPanel.setLayout(new GridLayout(2,1));
FormPanel.add(TextPanel);
FormPanel.add(BTPanel);
MainMenu.setContentPane(FormPanel);
MainMenu.pack();
MainMenu.show();
MainMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainMenu.setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
MainMenu.hide();
if(e.getActionCommand().equals("Inquire Balance") || e.getActionCommand().equals("Withdraw") || e.getActionCommand().equals("Deposit"))
{
//----------------------------------//
PINEnter = new JFrame("PIN");
JPanel PINTextPanel = new JPanel();
JPanel PINButtonPanel = new JPanel();
JPanel PINUniterPanel = new JPanel();
JLabel PINTextLabel = new JLabel("Please Enter PIN");
JTextField PINField = new JTextField(4);
JButton SubmitBT = new JButton("Submit PIN");
SubmitBT.addActionListener(this);
PINTextPanel.setBackground(Color.white);
PINTextPanel.add(PINTextLabel);
PINTextPanel.add(PINField);
PINButtonPanel.add(SubmitBT);
PINUniterPanel.setLayout(new GridLayout(2,1));
PINUniterPanel.add(PINTextPanel);
PINUniterPanel.add(PINButtonPanel);
PINEnter.setContentPane(PINUniterPanel);
PINEnter.setSize(360,140);
PINEnter.pack();
PINEnter.show();
PINEnter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PINEnter.setResizable(false);
PINNow = PINField.getText();
if(e.getActionCommand().equals("Inquire Balance")){OPTIONS = 1;}
else if(e.getActionCommand().equals("Withdraw")){OPTIONS = 3;}
else if(e.getActionCommand().equals("Deposit")){OPTIONS = 2;}
if(e.getActionCommand().equals("Submit PIN") && PINNow.equals(RealPin))
{ // switch and then some functions which are too long}
}
}
}
This is the code I'm working on, an ATM-Simulator. The only problem is when I get to PINEnter and then I would press the SubmitBT, It would not go to the other frames. PINEnter had a JTextField PINField and I should convert the content into a String PIN. In order to go to the other frames, PIN should be equal to String RealPin which is "1234". So if the Submit PIN button and PIN is equal to RealPin then it should be going on already with the other functions. I expected that when SubmitBT is pressed, with the PIN the same as RealPIN I should be going to the if statements but then, It didn't.
While syntactically you can do it - and it will compile, I don't think it will do what you're looking for. Let's look at your code:
if(e.getActionCommand().equals("Button in theFrame"))
{
newFramerz.show();
// If you got in here, then the value of e.getActionCommand() is "Button in theFrame"
if (e.getActionCommand().equals("Button in newFramerz"))
{
//The execution will never get here, because
//the value of e.getActionCommand() is "Button in theFrame"
//and hence will never be equal to "Button in newFramerz"
}
}
A more appropriate way of dealing with it would be:
String action = e.getActionCommand();
if(action.equals("Button in theFrame"))
{
newFramerz.show();
//whatever else
}
else if(action.equals("Button is newFramerz"))
{
//do something else
}

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