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

    Default How to import(read) a data file into 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); }
    }
        }

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

Similar Threads

  1. Read file in jtable
    By victoryo in forum New To Java
    Replies: 2
    Last Post: 01-11-2012, 12:19 PM
  2. Replies: 2
    Last Post: 03-25-2011, 02:36 PM
  3. Need a solution to read and store data from a file
    By sheetalnri in forum New To Java
    Replies: 10
    Last Post: 09-30-2010, 06:43 AM
  4. Import data from file into a gui
    By SBL in forum AWT / Swing
    Replies: 5
    Last Post: 11-21-2009, 04:10 PM
  5. Replies: 0
    Last Post: 04-17-2008, 07:36 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
  •