13 Replies - 2394 Views - Last Post: 27 April 2012 - 09:40 PM Rate Topic: -----

#1 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Java rewriting .txt file over and over again

Posted 27 April 2012 - 12:18 PM

I can't see how but my enter command is just rewriting name, number and note over and over again in the same spot. I thought with the addition of enter (\n) it would force it to the next line but it does not. Any pointers would be helpful.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.KeyStore.Entry;

public class PhonebookGUI {
	String enterString = "Enter", findString = "Find", listString = "List", deleteString = "Delete";
	private JFrame JFrame = new JFrame("Phonebook");
	JPanel actionPanel = new JPanel();
	JButton btnEnter = new JButton("Enter");
	JTextField nameText = new JTextField(10);
	JTextField numberText = new JTextField(10);
	JTextField noteText = new JTextField(20);
	JTextField findText = new JTextField(10);
	JTextArea listText = new JTextArea(15, 25);
	JScrollPane scrollPane = new JScrollPane(listText);
	JTextField deleteText = new JTextField(10);
	final JFileChooser fc = new JFileChooser();
	File file;
	
	// Create components & set hotkeys
	JRadioButton enterButton = new JRadioButton(enterString);
	JRadioButton findButton = new JRadioButton(findString);
	JRadioButton listButton = new JRadioButton(listString);
	JRadioButton deleteButton = new JRadioButton(deleteString);
	JMenuBar mb = new JMenuBar();
	JMenu mnuFile = new JMenu("File");
	JMenuItem mnuItemOpen = new JMenuItem("Open");
	JMenuItem mnuItemSave = new JMenuItem("Save");
	JMenuItem mnuItemQuit = new JMenuItem("Quit");
	JMenu mnuHelp = new JMenu("Help");
	JMenuItem mnuItemAbout = new JMenuItem("About");

	public PhonebookGUI() {
		// Create hotkeys
		enterButton.setMnemonic(KeyEvent.VK_E);
		enterButton.setActionCommand(enterString);
		findButton.setMnemonic(KeyEvent.VK_F);
		findButton.setActionCommand(findString);
		listButton.setMnemonic(KeyEvent.VK_L);
		listButton.setActionCommand(listString);
		deleteButton.setMnemonic(KeyEvent.VK_D);
		deleteButton.setActionCommand(deleteString);
		mnuItemOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.CTRL_MASK));
		mnuItemSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK));
		mnuItemQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.CTRL_MASK));
		mnuItemAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,ActionEvent.ALT_MASK));
		
		// Create a button group for the radio buttons
		ButtonGroup group = new ButtonGroup();
		group.add(enterButton);
		group.add(findButton);
		group.add(listButton);
		group.add(deleteButton);

		// Create a JPanel to throw the buttons onto & add the buttons &place the JPanel in the JFrame
		JPanel radioPanel = new JPanel(new GridLayout(0, 1));
		radioPanel.add(enterButton);
		radioPanel.add(findButton);
		radioPanel.add(listButton);
		radioPanel.add(deleteButton);
		JFrame.getContentPane().add(radioPanel, BorderLayout.WEST);

		// Add the menu bar to the JFrame & add the menu components to the menu
		JFrame.setJMenuBar(mb);
		mnuFile.add(mnuItemOpen);
		mnuFile.add(mnuItemSave);
		mnuFile.add(mnuItemQuit);
		mnuHelp.add(mnuItemAbout);
		mb.add(mnuFile);
		mb.add(mnuHelp);

		// Action listeners for the menu bar components, radio buttons and window closing
		JFrame.addWindowListener(new ListenCloseWdw());
		mnuItemOpen.addActionListener(new ListenMenuOpen());
		mnuItemSave.addActionListener(new ListenMenuSave());
		mnuItemQuit.addActionListener(new ListenMenuQuit());
		mnuItemAbout.addActionListener(new ListenMenuAbout());
		enterButton.addActionListener(new ListenAction());
		findButton.addActionListener(new ListenAction());
		listButton.addActionListener(new ListenAction());
		deleteButton.addActionListener(new ListenAction());
		btnEnter.addActionListener(new ListenbtnEnter());
	}
	
	public class ListenAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			// Action if "Enter" is selected
			if ("Enter".equals(e.getActionCommand())) {
				// Clear any previous entries and update the UI
				nameText.setText("");
				numberText.setText("");
				noteText.setText("");
				findText.setText("");
				listText.setText("");
				deleteText.setText("");
				actionPanel.removeAll();
				actionPanel.updateUI();
				
				// Place the new JPanel and add components to it
				actionPanel = new JPanel(new GridLayout(7, 7));
				actionPanel.add(new JLabel("Name: "));
				actionPanel.add(nameText);
				actionPanel.add(new JLabel("Number: "));
				actionPanel.add(numberText);
				actionPanel.add(new JLabel("Note: "));
				actionPanel.add(noteText);
				actionPanel.add(btnEnter);
				JFrame.getContentPane().add(actionPanel, BorderLayout.EAST);
				actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				actionPanel.repaint();

				// Update actionPanel
				actionPanel.updateUI();
			}
			// Action if "Find" is selected
			else if ("Find".equals(e.getActionCommand())) {
				// Clear any previous entries and update the UI
				nameText.setText("");
				numberText.setText("");
				noteText.setText("");
				findText.setText("");
				listText.setText("");
				deleteText.setText("");
				actionPanel.removeAll();
				actionPanel.updateUI();
				
				// Place the new JPanel and add components to it
				actionPanel = new JPanel(new GridLayout(7, 7));
				actionPanel.add(new JLabel("Find: "));
				actionPanel.add(findText);
				actionPanel.add(btnEnter);
				JFrame.getContentPane().add(actionPanel, BorderLayout.CENTER);
				actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				actionPanel.repaint();

				// Update actionPanel
				actionPanel.updateUI();
			}
			// Action if "List" is selected
			else if ("List".equals(e.getActionCommand())) {
				// Clear any previous entries and update the UI
				nameText.setText("");
				numberText.setText("");
				noteText.setText("");
				findText.setText("");
				listText.setText("");
				deleteText.setText("");
				actionPanel.removeAll();
				actionPanel.updateUI();
				
				// Read the Phonebook from the .txt file
				try {
				    FileReader fileReader = new FileReader(file);
				    BufferedReader bufferedReader = new BufferedReader(fileReader);
				    String line_from_file;
				    while ((line_from_file = bufferedReader.readLine()) != null)
				        listText.append(line_from_file + "\n");
				    bufferedReader.close();
				}
				catch(Exception e2) { System.out.println(e2); }
				
				// Throws the contact list into a message dialog
				listText.setEditable(false);
				JOptionPane.showMessageDialog(null, scrollPane, "Phonebook List", 1, null);

				// Update actionPanel
				actionPanel.updateUI();
			}
			// Action if "Delete" is selected
			else if ("Delete".equals(e.getActionCommand())) {
				// Clear any previous entries and update the UI
				nameText.setText("");
				numberText.setText("");
				noteText.setText("");
				findText.setText("");
				listText.setText("");
				deleteText.setText("");
				actionPanel.removeAll();
				actionPanel.updateUI();
				
				// Place the new JPanel and add components to it
				actionPanel = new JPanel(new GridLayout(7, 7));
				actionPanel.add(new JLabel("Delete: "));
				actionPanel.add(deleteText);
				actionPanel.add(btnEnter);
				JFrame.getContentPane().add(actionPanel, BorderLayout.CENTER);
				actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				actionPanel.repaint();
				
				// Update actionPanel
				actionPanel.updateUI();
			}

		}

	}
	
	public class ListenbtnEnter implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			// Get the entered contact
			String enter = "\n";
			
			// Action done upon confirmation under buttonEnter
			try 
			{
			  BufferedWriter fileOut = new BufferedWriter(new FileWriter(file));
			  fileOut.write(nameText.getText() + enter);
			  fileOut.write(numberText.getText() + enter);
			  fileOut.write(noteText.getText() + enter + enter);
			  fileOut.close();
			}
			catch (IOException ioe)
			{
			  ioe.printStackTrace();
			}
			
			// Clear any previous entries and update the UI
			nameText.setText("");
			numberText.setText("");
			noteText.setText("");
			findText.setText("");
			listText.setText("");
			deleteText.setText("");
			actionPanel.updateUI();
		}
	}
	
	// Action listener for Menu -> Quit
	public class ListenMenuQuit implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			System.exit(0);
			// TODO Auto-generated method stub
		}
	}
	
	// Action listener for Menu -> Open
	public class ListenMenuOpen implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == mnuItemOpen) {
				int state = fc.showOpenDialog(null);
				if(state == JFileChooser.APPROVE_OPTION) {
					file = fc.getSelectedFile();
				}
			}
		}
	}
	
	// Action listener for Menu -> Save
	public class ListenMenuSave implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try
			{
			  BufferedWriter fileOut = new BufferedWriter(new FileWriter(file));
			  fileOut.close();
			}
			catch (IOException ioe)
			{
			  ioe.printStackTrace();
			} 
		}
	}
	
	// Action listener for About -> Help
	public class ListenMenuAbout implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(null, "PhonebookGUI v1.0\n\n" +
					" The\"Enter\" command is for entering an new entry in your phonebook\n" +
					" The \"Find\" command is for searching your phonebook for a contact\n" +
					" The \"List\" command is for listing your phonebook in a seperate window\n" +
					" The \"Delete\" command is for deleting an entry in your phonebook\n\n" +
					" Use the \"Open\" link under File to open .txt Phonebook databases\n" +
					" Use the \"Save\" link under File to save your current Phonebook database", "PhonebookGUI Help", 2);
		}
	}
	
	// Action listener for closing the window
	public class ListenCloseWdw extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}

	}
	
	// Creating properties of the JFrame and applying them to the frame
	public void launchFrame() {
		JFrame.setPreferredSize(new Dimension(325, 225));
		JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JFrame.pack();
		JFrame.setVisible(true);
	}
	
	public static void main(String[] args) {
		PhonebookGUI gui = new PhonebookGUI();
		
		// Launching the GUI
		gui.launchFrame();
	}
}


Is This A Good Question/Topic? 0
  • +

Replies To: Java rewriting .txt file over and over again

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2197
  • View blog
  • Posts: 5,224
  • Joined: 10-September 10

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 12:43 PM

That's a lot of code to wade through for a single problem statement. Can you give us a clue where you think the problem lies? Maybe a tiny bit better explanation of the problem? What same spot? Is it in a component, at the console, where?
Was This Post Helpful? 0
  • +
  • -

#3 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 12:54 PM

View PostGregBrannon, on 27 April 2012 - 12:43 PM, said:

That's a lot of code to wade through for a single problem statement. Can you give us a clue where you think the problem lies? Maybe a tiny bit better explanation of the problem? What same spot? Is it in a component, at the console, where?


I have a random text file that I open. It looks like:

name
number
note
name
number
note

repeated about 50 times. I confirm that I loaded the file by clicking list which displays the file. Next I click enter to add a new name, number and note and click enter to confirm the addition of the contact. I then go to list to visually confirm the addition but the 50 entries are replaced with:

name
number
note

if I attempt to add more than one contact it only shows the latest addition i.e. if I also add:

random
text
here

the list file will only display:

random
list
here

when it should be

name
number
note

random
list
here

If I had to guess the problem is going to be centered around anything relating to "file" which is the universal name I used to reference the current, in use, .txt file. That would limit it to the btnEnter actionlistener, the mnuItemSave listener, the mnuItemOpen listener or the list else if statement in the radio button listener. However I have been staring at this group project that I have written by myself, with some help from this great community, and I can't see my error.
Was This Post Helpful? 0
  • +
  • -

#4 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,688
  • Joined: 19-March 11

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 12:56 PM

High-level question: you're aware that Java writes the whole file, right? You can't do edit-in-place with the java file io, you have to write the whole file.
So whatever String you send to the file is what will end up in the file. If you want to edit, you have to preserve the whole text, make your changes in memory, and send the whole thing out.

This seems like it might relate to your problem.

This post has been edited by jon.kiparsky: 27 April 2012 - 12:56 PM

Was This Post Helpful? 0
  • +
  • -

#5 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 12:58 PM

I did not know that, I assumed with the FileWriter I could dynamically edit a file. If that is the case, what would be the next best, simple, solution. A large array of type string and append it together?
Was This Post Helpful? 0
  • +
  • -

#6 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,688
  • Joined: 19-March 11

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 01:06 PM

Read the file into a StringBuilder and append the new content to it (or insert it in the middle, or whatever you like)
Was This Post Helpful? 0
  • +
  • -

#7 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2650
  • View blog
  • Posts: 11,179
  • Joined: 20-September 08

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 01:52 PM

You need to open the Writer in append mode

 BufferedWriter fileOut = new BufferedWriter(new FileWriter(file, true));

This post has been edited by g00se: 27 April 2012 - 01:52 PM

Was This Post Helpful? 2
  • +
  • -

#8 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 02:06 PM

Thanks for pointing that out. I was about halfway through building the code for the StringBuilder but I opened the write in append mode and that did the trick. Thanks again.
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 08:51 PM

FileWriter has a constructor that allow you to actually append to an existing file

http://docs.oracle.c...er(java.io.File, boolean)
Was This Post Helpful? 0
  • +
  • -

#10 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 08:53 PM

gOOse mentioned that. I believe I had the boolean argument empty which when corrected solved the issue.
Was This Post Helpful? 0
  • +
  • -

#11 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,688
  • Joined: 19-March 11

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 08:58 PM

Well, there you are. Shows that I need to spend some more time in the APIs, I guess.
Was This Post Helpful? 0
  • +
  • -

#12 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 09:00 PM

If it is any consolation jon, I was working on your StringBuilder idea and from what I had tested it was working very well but it was easier to add the boolean argument and uncomment that particualr code block.
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 09:17 PM

View Postjon.kiparsky, on 27 April 2012 - 11:58 PM, said:

Well, there you are. Shows that I need to spend some more time in the APIs, I guess.

Don't worry. It is an endless task :)
:^:
Was This Post Helpful? 0
  • +
  • -

#14 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,688
  • Joined: 19-March 11

Re: Java rewriting .txt file over and over again

Posted 27 April 2012 - 09:40 PM

Quote

If it is any consolation jon, I was working on your StringBuilder idea and from what I had tested it was working very well but it was easier to add the boolean argument and uncomment that particualr code block.


I don't know how many times I've said here that mistakes are the great teachers of this world. One of the things they can teach you, if you listen to them, is that what you know you know ain't necessarily so. It's not a bad thing to be reminded of this from time to time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1