Results 1 to 4 of 4
  1. #1
    leszer is offline Member
    Join Date
    Jun 2012
    Posts
    3
    Rep Power
    0

    Default Help importing (or reading) from text file to jtable

    Post Script, it seems to me this would be a simple matter of inverting the saveAction but for the life of me I don't see how to do it.

    Honestly, at this point I am willing to use a different class just to get it to read out.
    Last edited by leszer; 06-04-2012 at 05:36 AM.

  2. #2
    leszer is offline Member
    Join Date
    Jun 2012
    Posts
    3
    Rep Power
    0

    Default Help importing (or reading) from text file to jtable

    I'm trying to get a code that saves its entries to a text file from a jtable to read that text file when the application is run, so it can basically append new entries.

    But I'm pretty new to it all and I have failed every attempt. I've been googling my but off for four hours with zero success. I've found ways that use vector to build new tables for read the table but I would really like it to go into the one I already have created.

    Thanks for any help.

    Code below:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.lang.Exception;
    import java.io.*;
    import java.io.File;
    
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    public class Contacts extends JFrame implements ActionListener 
    	{
    
    	private JTextField CName = new JTextField(20);
    	private JTextField CAge = new JTextField(10);
    	private JTextField CEmailAddress = new JTextField(10);
    	private JTextField CCellNumber = new JTextField(10);
    	
    	private JButton enterBtn = new JButton("Enter");
    	private JButton clearBtn = new JButton("Clear");
            private JButton saveBtn = new JButton("Save");
    	private JButton exitBtn = new JButton("Exit");
    	private DefaultTableModel tableModel;
    	
    	
    	int contactCount = 0;
    	
    	public Contacts() 
    	{
    		super("Contact Entry");
    		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    		setVisible(true);
    		setResizable(false);
    		
    		// labels for everything
    		JPanel inputSectionPanel = new JPanel();
    		JLabel nameLabel = new JLabel("Name");
    		JLabel ageLabel = new JLabel("Age");
    		JLabel emailLabel = new JLabel("Email Address");
    		JLabel numberLabel = new JLabel ("Cell Number");
                    
    		inputSectionPanel.add(nameLabel);
    		inputSectionPanel.add(CName);
    		
    		inputSectionPanel.add(ageLabel);
    		inputSectionPanel.add(CAge);
    		
    		inputSectionPanel.add(emailLabel);
    		inputSectionPanel.add(CEmailAddress);
                    inputSectionPanel.add(numberLabel);
    		inputSectionPanel.add(CCellNumber);
                    
    		//place for buttons	
    		JPanel buttonPanel = new JPanel();
    		JTable contactTable = new JTable();
    
    		enterBtn.addActionListener(this);
    		clearBtn.addActionListener(this);
    		exitBtn.addActionListener(this);
                    saveBtn.addActionListener(this);
    		buttonPanel.add(enterBtn);
    		buttonPanel.add(clearBtn);
                    buttonPanel.add(saveBtn);
    		buttonPanel.add(exitBtn);
    
    		// table layout
    		Container tableButtonContainer = getContentPane();
    		tableButtonContainer.setLayout(new BorderLayout());
    		tableButtonContainer.setLayout(new BoxLayout(tableButtonContainer, BoxLayout.Y_AXIS));
    		tableButtonContainer.add(inputSectionPanel, BorderLayout.WEST);
    
    		// table with 4 columns
    		tableModel = new DefaultTableModel(0,4);
    		
                    // Name columns
    		String col[] =  {  "Name", "Age", "Email Address", "Cell Number"  };
    		tableModel.setColumnIdentifiers(col);
    		contactTable.setModel(tableModel);
    		
                    
    		// create pane for table
    		JScrollPane tableScroller =
    				new JScrollPane(contactTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    
    		tableScroller.setViewportView(contactTable);
    		tableButtonContainer.add(contactTable, BorderLayout.CENTER);
    		tableButtonContainer.add(buttonPanel, BorderLayout.SOUTH);
    		tableButtonContainer.add(tableScroller);
    		tableScroller.setViewportView(contactTable);
    		pack();
    
    	}
    
    //buttons actions	
    	public void actionPerformed(ActionEvent event)
    	{
    		JButton source = (JButton) event.getSource();
    		if (source == enterBtn) 
    		{
    			enterContact();//-----------------------------------------------
    		} 
    		else if (source == clearBtn) 
    		{
    			clearValues();
    		} 
                    else if (source == saveBtn)
                    {
                            saveAction();
                    }    
    		else if (source == exitBtn) 
    		{
    			quit();
    		}
    	}
    
    //Exception handling on all entries
    	void enterContact() 
    	{
    			
    		// test contact
    		String contact = CName.getText();
    		if (contact == null || contact.equals("")) 
    		{
    			JOptionPane.showMessageDialog(null, "Please enter a validname", "Error", JOptionPane.ERROR_MESSAGE);
    			return;
    		}
    		
                    //test age betweeen 0 and 120
    		
                    String age = CAge.getText();
    		
                    Integer.parseInt(age);    
                    if (Integer.parseInt(age) > 0 && Integer.parseInt(age) < 121); 
                       else {
                      System.err.println("Please enter a valid age between 0 and 120");
                      return;
                    }
                        
    
    		
            
    		// test email
                    
    		String email = CEmailAddress.getText();
    		if ( email == null || email.equals(""))
                    {
                            JOptionPane.showMessageDialog(null, "Please Enter a valid Email Address", "Error", JOptionPane.ERROR_MESSAGE);
                            return;
                    }
    	
                    //test cell number
                    
                    String cell = CCellNumber.getText();
                    try 
                    {
                        Integer.parseInt(cell);
                            }
                          catch(Exception e) {
                              System.out.println("Please enter a valid numeric phone number");
                              return;
            }
    		
    		//determine row count and add values from text fields
    		tableModel.setRowCount(contactCount + 1);
    		tableModel.setValueAt(contact, contactCount, 0);
    		tableModel.setValueAt(age, contactCount, 1);
    		tableModel.setValueAt(email, contactCount, 2);
                    tableModel.setValueAt(cell, contactCount, 3);
    		contactCount++;
    
    	}
    
    //Clear values 
    	void clearValues() 
    	{
    		CName.setText(null);
    		CAge.setText(null);
    		CEmailAddress.setText(null);
                    CCellNumber.setText(null);
    	}
    
    //exit application 
    	void quit() 
    	{
    		System.exit(0);
    	}
    
    	public static void main(String args[]) 
    	{
    		java.awt.EventQueue.invokeLater(new Runnable() 
    		{
    			public void run() 
    			{
    				new Contacts().setVisible(true);
    			}
    		});
    	}
    
            
       
      public void saveAction(){
        
            File file = new File("data.dat");
          
          try{
                  
            FileWriter data = new FileWriter(file);
    
            for(int i = 0; i < tableModel.getColumnCount(); i++){
                data.write(tableModel.getColumnName(i) + "\t");
            }
            
           data.write("\r\n");
    
            for(int i=0; i< tableModel.getRowCount(); i++) {
                for(int j=0; j < tableModel.getColumnCount(); j++) {
                    data.write(tableModel.getValueAt(i,j).toString()+"\t");
                }
                data.write("\r\n");
            }
    
            data.close();
    
        }catch(IOException e){ System.out.println(e); }
    }
        }

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help importing (or reading) from text file to jtable

    Unless I have missed something this has nothing to do with applets (things that typically live on web pages, and manipulate their resources with the help of a web browser). I'll move to the Swing forum.

    Again, I may have missed it, but what, exactly, is the problem: ie how does the behaviour of what you have posted differ, when run, from the expected or intended behaviour?

    -----

    Just a guess - and others more knowledgeable about such things can/will jump in to correct me - but I would have considered writing a subclass of TableModel (maybe extending DefaultTableModel) that was able to load and save its data from file. The idea is to stop Contacts (a frame ie some sort of view) from doing everything itself and becoming long and complex in the process. And for that matter I'd make Contracts a panel not a frame - a thing combining a bunch of components and providing behaviour to coordinate them.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help importing (or reading) from text file to jtable

    it seems to me this would be a simple matter of inverting the saveAction
    Try that.

    The load action would have to read the file. From the first line it would obtain a list (Vector instance) of column names. Then, line by line, it would build up a list of lists containing the data. Finally it would use these lists (of column names and data) to create a new table model and set the table's model to this new model. Contact would have to "remember" the table whose model it is going to alter: ie contactTable would have to be an instance variable not a variable local to the constructor.

Similar Threads

  1. Replies: 8
    Last Post: 07-17-2011, 03:38 PM
  2. Replies: 8
    Last Post: 06-30-2011, 02:20 PM
  3. Reading from file and adding to JTable
    By purple in forum New To Java
    Replies: 11
    Last Post: 04-14-2011, 11:33 PM
  4. Writing and Reading data to and from xml file to JTable
    By ramihemang90 in forum Advanced Java
    Replies: 3
    Last Post: 03-15-2011, 03:07 PM
  5. Replies: 6
    Last Post: 12-12-2008, 04:35 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •