1

Hi i am reading a text file into JTable, but here is what my JTable Looks Like Now: enter image description here

How can I format it correctly and allow JTable to be editable by users?

My Text File: File Name(people.txt)

COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY  COLUMN_DEFAULT  EXTRA   
Names   VARCHAR(500)    NO  
Address VARCHAR(500)    NO

Coding so far:

 import java.io.*;
 import java.awt.*;
 import java.util.*;
 import javax.swing.*;
 import java.awt.event.*;
 import javax.swing.table.*;

   public class stackq extends AbstractTableModel {
    Vector data;
    Vector columns;

    public stackq() {
            String line;
            data = new Vector();
            columns = new Vector();
            try {
                    FileInputStream fis = new FileInputStream("D:/joy/text/people.txt");
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
                    while (st1.hasMoreTokens())
                            columns.addElement(st1.nextToken());
                    while ((line = br.readLine()) != null) {
                            StringTokenizer st2 = new StringTokenizer(line, " ");
                            while (st2.hasMoreTokens())
                                    data.addElement(st2.nextToken());
                    }
                    br.close();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }

    public int getRowCount() {
            return data.size() / getColumnCount();
    }

    public int getColumnCount() {
            return columns.size();
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
            return (String) data.elementAt((rowIndex * getColumnCount())
                            + columnIndex);
    }

     public String getColumnName(int i){
         return (String)columns.get(i);
              }


      public static void main(String s[]) {
            stackq model = new stackq();
            JTable table = new JTable();
            table.setModel(model);
           JScrollPane scrollpane = new JScrollPane(table);
            JPanel panel = new JPanel();
            panel.add(scrollpane);
            JFrame frame = new JFrame();
            frame.add(panel, "Center");
            frame.pack();
            frame.setVisible(true);
         }
      }

Thank You So much.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • 1
    Interestingly, when I copy/paste that text content as a String into the source and run it, I get a quite different result than seen above - with distinct columns. Are the values in the original file separated by spaces or a tab character or something else? – Andrew Thompson Apr 17 '13 at 06:24
  • COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA Names VARCHAR(500) NO Address VARCHAR(500) NO – Shaiju T Apr 17 '13 at 06:27
  • hi andrew , copy the above to source text now and run, this will work now – Shaiju T Apr 17 '13 at 06:29
  • @your pictures looks very strange, just like @Andrew said. If you want table to be editable, you can use `table.setCellEditable(true)` and register a `Table Cell Listener` to table, after stopping editing, you can call `setValueAt()` to set the new value to table model, you can google for it. – hiway Apr 17 '13 at 06:35
  • *"..this will work now"* No, it won't since my system does not have a file at `D:/joy/text/people.txt`. Why do you think I turned the data to a `String` in the 1st place? Also, when I ask a question, answer it. I ask these questions for *your* benefit, in order to try and progress towards a solution, rather than to hear myself talk. – Andrew Thompson Apr 17 '13 at 07:00
  • hi Andrew, sorry for that, by the way the values are separated by TAB – Shaiju T Apr 17 '13 at 07:15
  • 1
    @tim don't you think that you should then use a `new StringTokenizer(line, "\t")`? You specify the white space as being the separator of your columns while it is actually tabs, so the tokenizer will return the whole line as a single token. – Guillaume Polet Apr 17 '13 at 07:37
  • oh thank you so much Guillanume Polet, new StringTokenizer(line, "\t"), works fine now all my data's are separated, do you know how can i edit my cell's in table and update it – Shaiju T Apr 17 '13 at 07:50
  • @tim override `isCellEditable` and `setValueAt` in your `AbstractTableModel` – Guillaume Polet Apr 17 '13 at 08:02
  • @Guillanume Polet i did this as you said, but i get this error Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true ; } Override public void setValueAt(Object aValue, int row, int column) { Vector rowVector = (Vector) data.elementAt(row); rowVector.setElementAt(aValue, column); fireTableCellUpdated(row, column); } Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Vector at Stackq.setValueAt(Stackq.java:49) – Shaiju T Apr 17 '13 at 08:34
  • hi i have posted my new question here :http://stackoverflow.com/questions/16056222/update-the-jtable-at-runtime , ok how to give points for you ? i dont see any green tick mark near you @Guillanume Polet – Shaiju T Apr 17 '13 at 09:22

3 Answers3

1
public Stackq() {
String line;
data = new Vector();
columns = new Vector();
int count = 0;
try {
    FileInputStream fis = new FileInputStream("D:\\1.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
    while (st1.hasMoreTokens()) {
    columns.addElement(st1.nextToken());
    count++;
    }
    while ((line = br.readLine()) != null) {
    StringTokenizer st2 = new StringTokenizer(line, " ");
    for (int i = 0; i < count; i++) {
        if (st2.hasMoreTokens())
        data.addElement(st2.nextToken());
        else
        data.addElement("");
    }
    }
    br.close();
} catch (Exception e) {
    e.printStackTrace();
}
}

Just add one count variable for header count, and add the empty string into the data vector where tokenizer returns null.

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93
  • hi, i did run your code, but still it shows the same : http://imagesup.net/?di=713661785967 – Shaiju T Apr 17 '13 at 06:45
  • hi that is so good to see, i have made the edit , have look at my whole code: http://textuploader.com/?p=6&id=KIoC7, still it doesn't shows like you – Shaiju T Apr 17 '13 at 07:07
  • no it isn't working. did you check my code ? is your code matching mine ? please help me – Shaiju T Apr 17 '13 at 07:27
  • I run your code on my machine and it is completely working fine. – eatSleepCode Apr 17 '13 at 07:31
  • hi this was needed, new StringTokenizer(line, "\t"), works fine now all my data's are separated, do you know how can i edit my cell's in table and update it – Shaiju T Apr 17 '13 at 07:51
  • I don't know why this is not working for you. To table cell editable use table.setCellEditable(true). – eatSleepCode Apr 17 '13 at 08:59
  • hi ya i have done that, but now this is my new error hope you can help me with ideas: http://stackoverflow.com/questions/16056222/update-the-jtable-at-runtime – Shaiju T Apr 17 '13 at 09:26
0

Why don't you use the DefaultTableModel to represent the data in your table? It will take care of all the Swing-related stuff for you, and you can easily add columns or rows to it, using addColumn(Object) and addRow(Object[]), respectively.

First, you would create a DefaultTableModel object.

Then, instead of doing creating a Vector columns, you'd just fill the model by doing

model.addColumn(st1.nextToken()); // (for adding a column)

or

Vector row = new Vector();
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens()) {
    row.add(st2.nextToken());
}
result.addRow(row); // for adding a row
mthmulders
  • 9,483
  • 4
  • 37
  • 54
0

Try this If you are using NetBean, where you can bind List of Object to table and Bind Column with respective value empMList is list of Employee.

org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, empMList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Address");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Employee Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
JavaSun
  • 58
  • 7