I am writing a program in which I have done ALOT of coding already but there are still problems and features to be added.

So far my program:

1) Takes data from a .dat file and displays it on a table
2) There is a button for which you can add to the .dat file

Concerning the .dat file, it is organized into lines. Each line is data for a member....for example:

12345678Kenneth Wardman Westfirst High School 2007I12500

That is the first line of my data file..first 8 characters are the member #, next 20 is the member name, next 25 is the member school, next 4 is the year joined, next 1 is I/A for inactive/active, and the next 5 characters represent the $ owed. This pattern is inherent for all the lines of the .dat file

I have a function that successfully splits each line into sections and displays them in an organized fashion. I also have a function (as i said before) thats prompts the user for info and then adds the line to the .dat file in the above format.

What I have left to do is:

1) Make it so I can somehow change the member data (you'll see how i've organized things it in my code that i have attached)

2) Make it so that the table can "refresh" so i don't have to exit and then rerun the program in order to view the changes (the lines that I've added)

3) Get the button BELOW the table rather than covering the top part of the table (i stink at swing).

4) For some reason, my actionlistener doesnt function quite right. I wrote

source = event.getSource(); //event is the actionlistener parameter

if (source == addInfo) //addInfo is the name of my button
//at this point it says that addInfo is initialized or somthing...

This is in my code that is attached.

I have attached my .java files and the .dat file as .txt files. (just incase people are suspicious...)

model.txt -> copy and paste text into notepad and save as model.java
table.txt -> copy and paste text into notepad and save as table.java and put in same folder as model.java
nlc2008.txt -> copy and paste text into notepad and save as nlc2008.dat and put in the same folder (or whereever it needs to be for the file to be found by the program)
I really am in desperate need of expert advice....

Thanks in advance!

model.txt

table.txt

nlc2008.txt

Attachments
//DOCUMENT EVERYTHING
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;

//this class serves as a template for the "table" class
public class model extends AbstractTableModel {
    
    protected Vector data;
    protected Vector columnNames ;
    protected String datafile;
    
    protected model(String f){
        datafile = f;
        initVectors();
    }
    
    private void initVectors() {
        
        String aLine ;
        data = new Vector(); //vector containing data
        columnNames = new Vector(); //vector just for the columns
        
        try {
            FileInputStream fin =  new FileInputStream(datafile); //inputs data from a txt/dat file
            BufferedReader br = new BufferedReader(new InputStreamReader(fin));
            
            //add all the names of the columns
            columnNames.addElement("Number");
            columnNames.addElement("Name");
            columnNames.addElement("School");
            columnNames.addElement("Year");
            columnNames.addElement("Activity");
            columnNames.addElement("Amount Owed");
            
            //adds the data from the file to the "data" vector
            //based on lines
            while ((aLine = br.readLine()) != null){
            	
            	String[] characters = new String[aLine.length()];
            	for (int i=0; i<aLine.length(); ++i)
            	{
            		characters[i] = String.valueOf(aLine.charAt(i));
            	}
            	
            	data.addElement(numCutter(characters)); //see the numCutter function below
            	data.addElement(nameCutter(characters));
            	data.addElement(schoolCutter(characters));
            	data.addElement(yearCutter(characters));
            	data.addElement(actCutter(characters));
            	data.addElement(owedCutter(characters));      	
            }
            
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
    
    public static void addData(String str){
    	try {
            BufferedWriter out = new BufferedWriter(new FileWriter("nlc2008.dat", true));
            out.write(str);
            out.newLine();
            out.close();
        } catch (IOException e) {
        }
    }

    //is it possible to have a method to change certain lines of the .dat file? 
    //if you have run table.java, then you will see how there are names and numbers for each member
    //i would like to somehow be able to change individual data
        
    /*these functions cut down the text from the .dat file and lets me 
    cut the text into different sized bits, and up in the constructor 
    i store these "cut" values into the array*/
    private String owedCutter(String[] toParse) {
    	String owed = "";
    	for (int i=58; i<63; ++i){
    		owed += toParse[i];
    	}
		return owed;
	}

	private String actCutter(String[] toParse) {
		String act = "";
		for (int i=57; i<58; ++i){
    		act += toParse[i];
    	}
		if (act.equalsIgnoreCase("I"))
		{
			act = "Inactive";
			return act;
		}
		
		else if (act.equalsIgnoreCase("A"))
		{
			act = "Active";
			return act;
		}
		else 
			return act;
	}

	private String yearCutter(String[] toParse) {
		String year = "";
		for (int i=53; i<57; ++i){
    		year += toParse[i];
    	}
		return year;
	}

	private String schoolCutter(String[] toParse) {
		String school = "";
		for (int i=28; i<53; ++i){
    		school += toParse[i];
    	}
		return school;
	}

	private String nameCutter(String[] toParse) {
		String name = "";
		for (int i=8; i<28; ++i){
    		name += toParse[i];
    	}
		return name;
	}

	private String numCutter(String[] toParse) {
		String num = "";
		for (int i=0; i<8; ++i){
    		num += toParse[i];
    	}
    	return num;
	}

	public int getRowCount() {
        return data.size() / getColumnCount();
    }
    
    public int getColumnCount(){
        return columnNames.size();
    }
    
    public String getColumnName(int columnIndex) {
        String colName = "";
        
        if (columnIndex <= getColumnCount())
            colName = (String)columnNames.elementAt(columnIndex);
        
        return colName;
    }
    
    public Class getColumnClass(int columnIndex){
        return String.class;
    }
    
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }
    
    public Object getValueAt(int rowIndex, int columnIndex) {
        return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    }
    
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        return;
    }
}
12345678Kenneth Wardman     Westfirst High School    2007I12500
21569210Jeff Foxworthy      Northeast High School    2008A02500
87656743Hillary Kerry       Spring Community College 2006I02475
00098768Everett Lovell      Yale University          2007A02200
12309876Dawn Montana CollyerUniversity California Ber2008I02099
48121620Freddie MacArther   Westfirst High School    2006A00000
//DOCUMENT EVERYTHING
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;

public class table extends JPanel implements ActionListener{
    public table(String dataFilePath) {
        JTable table;
        model model;
        Font f;
        JButton addInfo;
        
        f = new Font("SanSerif",Font.PLAIN,24);
        setFont(f);
        setLayout(new BorderLayout());
        
        model = new model(dataFilePath);
        
        table = new JTable();
        table.setModel(model);
        table.createDefaultColumnsFromModel();
        
        GridLayout layout = new GridLayout(80,30);
        
        addInfo = new JButton("Add Data");
        addInfo.setSize(80, 30);
        addInfo.addActionListener(this); //action listener is somewhere below
        
        //i'm not good at swing...and I don't know how to make the button 
        //appear AFTER the table rather than right on top of it...
        //I could use some advice here...but not the most important of things
        add(addInfo);
        
        JScrollPane scrollpane = new JScrollPane(table);
        add(scrollpane);
        
        try{
        	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        	SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e){
        	System.out.println("Can't set look and feel:" + e.getMessage());
        	e.printStackTrace();
        }
    }
    
    public void actionPerformed(ActionEvent event){
    	Object source = event.getSource(); 
    	String addLine;
    	String trimmer;
    	
    	//if (source == addInfo){ for some reason this doesnt work, and i don't know why
    	
    		trimmer = JOptionPane.showInputDialog("Enter Member Number");
    		if (trimmer.length() != 8)
    		{
    			while(trimmer.length() < 8){
    				trimmer += " "; 
    			}
    		}
    		addLine = trimmer.substring(0, 8);
    		
    		trimmer = JOptionPane.showInputDialog("Enter Member Name");
    		if (trimmer.length() != 20)
    		{
    			while(trimmer.length() < 20){
    				trimmer += " "; 
    			}
    		}
    		addLine += trimmer.substring(0,20);
    		
    		trimmer = JOptionPane.showInputDialog("Enter Member's School");
    		if (trimmer.length() != 25)
    		{
    			while(trimmer.length() < 25){
    				trimmer += " "; 
    			}
    		}
    		addLine += trimmer.substring(0,25);
    		
    		trimmer = JOptionPane.showInputDialog("Enter the Year Joined");
    		if (trimmer.length() != 4)
    		{
    			while(trimmer.length() < 4){
    				trimmer += " "; 
    			}
    		}
    		addLine += trimmer.substring(0,4);
    		
    		trimmer = JOptionPane.showInputDialog("Enter I/A (for Inactive or Active)");
    		if (trimmer.equalsIgnoreCase("inactive") || trimmer.equalsIgnoreCase("i"))
    			trimmer = "I";
    		else if (trimmer.equalsIgnoreCase("active") || trimmer.equalsIgnoreCase("a"))
    			trimmer = "A";
    		
    		addLine += trimmer;
    		
    		trimmer = JOptionPane.showInputDialog("Enter Amount Owed");
    		if (trimmer.length() != 5)
    		{
    			while(trimmer.length() < 5){
    				trimmer += " "; 
    			}
    		}
    		addLine += trimmer.substring(0,5);
    		
    		model.addData(addLine); //calling addData function from model, to write to file

    }
    public Dimension getPreferredSize(){
        return new Dimension(800, 400);
    }
    
    public static void main(String s[]) {
        JFrame frame = new JFrame("Current Account Balances");
        table panel;
        
        panel = new table("nlc2008.dat");
        
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setForeground(Color.black);
        frame.setBackground(Color.lightGray);
        frame.getContentPane().add(panel,"Center"); 
                
        frame.setSize(panel.getPreferredSize());
        frame.setVisible(true);
        frame.addWindowListener(new WindowCloser());
    }
}

class WindowCloser extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        Window win = e.getWindow();
        win.setVisible(false);
        System.exit(0);
    }
}

People are normally averse to opening attachments; it would be better to paste the *relevant* piece of code and describe a *single* problem at a time rather than confusing the reader with a lot of details.

For class names use first letter big. (public class Table)
You need decide where your data is first plane. Inside table-model or inside file?

a few clarifications inside code-text
-ActionListener - button recognize
-Layout
-ViewportView scroll bar policy
-table.repaint
-table-model update

//DOCUMENT EVERYTHING
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Table extends JPanel implements ActionListener {

    // make table as Table-class member, to be visible inside
    // public void actionPerformed(ActionEvent event) {
    private JTable table;//////
    private static final String ADD_DATA = "Add Data";/////////////

    public Table(String dataFilePath) {
        Model model;
        Font f;
        JButton addInfo;
        f = new Font("SanSerif", Font.PLAIN, 24);
        setFont(f);
        setLayout(new BorderLayout());
        model = new Model(dataFilePath);
        table = new JTable();
        table.setModel(model);
        table.createDefaultColumnsFromModel();
        table.setFillsViewportHeight(true);////////////MAGIC LINE
        //GridLayout layout = new GridLayout(80, 30);

        addInfo = new JButton(ADD_DATA) {
            //@Override

            public Dimension getPreferredSize() {
                return new Dimension(80, 30);
            }
        };
        // addInfo.setSize(180, 30); 
        addInfo.addActionListener(this); //action listener is somewhere below
        //i'm not good at swing...and I don't know how to make the button 
        //appear AFTER the table rather than right on top of it...
        //I could use some advice here...but not the most important of things
        JPanel buttonPanel = new JPanel();/////////////
        buttonPanel.setLayout(new FlowLayout());///////
        buttonPanel.add(addInfo);//////////////////////
        add(buttonPanel, BorderLayout.SOUTH);//////////
        //////////////

        JScrollPane scrollpane = new JScrollPane();
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, new JLabel("#"));
        scrollpane.setWheelScrollingEnabled(true);//for future use
        scrollpane.setViewportView(table);
        add(scrollpane, BorderLayout.CENTER);///////////

        //LAF......
    }

    public void actionPerformed(ActionEvent event) {
        // to look
        System.out.println(event);
        System.out.println(event.getSource());
        System.out.println(event.getSource().getClass());
        System.out.println(event.getSource().getClass().equals(JButton.class));
        if ((event.getSource().getClass().equals(JButton.class))) {
            String source = ((JButton) event.getSource()).getText();
            if (source.equals(ADD_DATA)) {
                System.out.println(source);
               // your ADD_DATA button code
              
/// trimmer...

               Model.addData(addLine); //calling addData function from model, to write to file  //// and to write to table-model

              table.repaint();////////////////////////////
            }
        }
    }
///.... rest
}

Make a possibility to update table-model
// split to two separate methods ?

public class Model extends AbstractTableModel {
//...
    public static void addData(String str) {
        //part 1 - add data to model
       // same code - redundant! - same as used during read from file
       // make reuseble
        String[] characters = new String[str.length()];
        for (int i = 0; i < str.length(); ++i) {
            characters[i] = String.valueOf(str.charAt(i));
        }
        // make xxxCutter(characters) methods - static 
        data.addElement(numCutter(characters)); //see the numCutter function below
        data.addElement(nameCutter(characters));
        data.addElement(schoolCutter(characters));
        data.addElement(yearCutter(characters));
        data.addElement(actCutter(characters));
        data.addElement(owedCutter(characters));
        //part 2 - add data to file
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("nlc2008.dat", true));
            out.write(str);
            out.newLine();
            out.close();
        } catch (IOException e) {
        }
    }
//...
}
This article has been dead for over six months. Start a new discussion instead.