i have created an app which reads lines from a .txt file, splits the line at a " " and then stores them in a ArrayList which then gets put in a JTable.

i created 27 columns and named them... now i want to add an extra column on the end but make each row a JComboBox.

i added an extra column in my JTable called HI:

private class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Name" , "Age", "Pos", "Nat", "St", "Tk", "Ps", "Sh", "Ag", "Kab", "Tab", "Pab", "Sab", "Gam", "Sub", "Min", 
"Mom", "Sav", "Con", "Ktk", "Kps", "Sht", "Gls", "Ass", "DP", "Inj", "Sus","HI"};
     

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return rosterList.size();
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

      
        public Object getValueAt(int row, int col) 
               {
               return rosterList.get(row)[col];
        }
                        
    }

i tried using this:

int index1 = 27;
        TableColumn col1 = table.getColumnModel().getColumn(index1);
            
           javax.swing.JComboBox comboBox = new javax.swing.JComboBox();       
           ArrayList list = new ArrayList();
           list.add("GK");
           list.add("DFC");
           for (int i = 0; i < list.size(); i++)
           {           
               comboBox.addItem(list.get(i)); 
            }
            col1.setCellEditor(new javax.swing.DefaultCellEditor(comboBox));

it wont compile and i get this error:
java.lang.ArrayIndexOutOfBoundsException: 27 >= 27

i think its got something to do with the reading of the .txt file because it only has 26 columns in the file.

how would i fix it?

The rest of the error stack trace would tell you which line the error is occurring on. Read it carefully and you won't have to "think it's got something to do with" anything - you'll know.

The rest of the error stack trace would tell you which line the error is occurring on. Read it carefully and you won't have to "think it's got something to do with" anything - you'll know.

ok i got it to compile and display by making the getValueAt () method in MyDataTable to return null when it reaches the last column.

still cant get the combobox to display though :S

ok got the column to be a Combobox (didnt have cell editing enabled)... but now when i select something from the combobox in a cell it doesnt remain selected, just go's blank.

tried using :

public void setValueAt(Object value, int row, int col) {
         value = rosterList.get(row)[col];
        fireTableCellUpdated(row, col);
                                               
    }

but i get an array index out of bounds 27, error... which points to value = line...

any ideas?

Once you select the item in the combo box, it will appear in the JTable automatically, using whatever the default JTable code is, so you must have overridden a method or something. Anyway,

return rosterList.get(row)[col];

What does that do? Looks like it causes an error. If you go to your error message like Ezzaral said, let us know if it points to that line.

the error points to:

value = rosterList.get(row)[col];

the one you are talking about returns the String value in the Array List at each location..

eg row 0, col 0.... row 0 col 1... row 1 col 0 etc..

No, it doesn't. It causes an error because the code doesn't make any sense. Where else have you seen ()[] and brackets used interchangeably?

That syntax actually does work fine with something like List<String[]>. I would imagine you are getting that error because you did not add an element in the 'rosterList' arrays to hold the data for that column you added to your model. Your model needs to also have a place to store that column data, which entails more than just adding a column name for it.

ok well ive been advised to use the DefaultTableModel for this sort of thing instead of creating a custom TableModel.... umm how would i put my rows of data into a 2d String Array?

J.Langfield   28 LRC sco 16  1  1  1 28 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
J.Bateman     19 LRC eng 14  1  1  1 21 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
B.Bossu       27 LRC fra 14  1  1  1 25 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
L.Mair        27  RC sco  1 21  4  5 26 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
S.Duff        26  LC sco  1 22 10  3 27 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
A.Considine   21   C sco  1 20  4  5 25 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
Z.Diamond     23  RC sco  1 21  7  4 24 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
C.Mulgrew     21  LC sco  1 21 15  4 25 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
R.Foster      22  LR sco  1 20 14  1 26 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
S.Severin     29   C sco  1 13 22  2 27 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
M.Kerr        26   C sco  1  9 21  9 28 300 300 700 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0

right now i have a textRead() method for reading the text into an arraylist... what would i need to change for a 2D array? :S
is it a simular thing? declare a 2D array and just use an add method with rowfields?

private void textRead() 
  {
      
     
     
     try
    {
      yahoo = new URL("http://www.afterextratime.net/game/spa/Ars.txt");
        URLConnection yc = yahoo.openConnection();
        BufferedReader br = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String line = br.readLine();                        
        
      while (line != null )
      {
        String [] rowfields = line.split("[ ]+");
        rosterList.add(rowfields);
        
        line = br.readLine();
       }
     
    }
    catch (FileNotFoundException e)
    {
      // can be thrown when creating the FileReader/BufferedReader
      // deal with the exception
      e.printStackTrace();
    }
    catch (IOException e)
    {
      // can be thrown by br.readLine()
      // deal with the exception
      e.printStackTrace();
    }
        
}

The ArrayList of String[] is not really a problem if you want to keep it, but you need to add space to store the data for the column you are adding. To do that, you would need to copy the split() result to a larger array

while (line != null )
      {
        String [] rowfields = line.split("[ ]+");
        // copy into a new array that is one element larger
        String[] columnData =  Arrays.copyOf(rowfields, rowfields.length + 1);
        rosterList.add(columnData);
        
        line = br.readLine();
       }
    }

You could, of course, also use a List or Vector to hold your row data, but that would require changing more of your existing code.

Ok, well I stand corrected. My apologies.

It certainly does look invalid and only works with specifically typed Lists - definitely an easy candidate to trip the syntax alarm bells :)

thanks for replying mate.. that part has fixed the errors from when i pick something in the ComboBox but i still cant get the combobox cell to get updated with my selection?

ive tried using:

public void setValueAt(Object value, int row, int col) {
        value = rosterList.get(row)[col];
        fireTableCellUpdated(row, col);
    }

no luck. any ideas?

here is my fullcode, its a bit messy but ill tidy it up at the end.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton.*;
import javax.swing.event.ListSelectionEvent;


public class panel extends JFrame
{
    private JTable table;
    private JButton button;
    ArrayList<String[]> rosterList = new ArrayList<String[]>();
    private JPanel buttonpanel;
    private JScrollPane scrollPane;
    private JPanel test;
    private JButton button1;
    private JPanel buttonpanel1;
    private JPanel scroll;
    private JPanel combo;
    private JTextArea textArea;
    private FlowLayout exp;
    private BoxLayout box;
    String [] positions = {"GK", "DFC","DFC","DFL","DFR","MF"};
    private JComboBox gkBox;
    private JComboBox gkBox1;
    URL yahoo;
    private JComboBox comboBox;
 

    public panel()
    {
        setTitle("Roster Sorter");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFrame.setDefaultLookAndFeelDecorated(true);
       
        textRead();
        jTable();
        jButton();
        box = new BoxLayout(scroll,BoxLayout.PAGE_AXIS);
        exp = new FlowLayout();
        scroll.setLayout(new BoxLayout(scroll, BoxLayout.PAGE_AXIS));
        add(scroll);
        add(buttonpanel,BorderLayout.PAGE_END);
        pack();
        setVisible(true);
           
        
               
    }
    
        
        private void jTable()
        {
            
            
            TableModel myData = new MyTableModel(); 
            table = new JTable(myData); 
            
            gkBox = new JComboBox(positions);
            gkBox.setSelectedIndex(0);
            gkBox.addActionListener(new ComboBoxListener());
            TableColumn genderCol = table.getColumnModel().getColumn(27);
            genderCol.setCellEditor(new DefaultCellEditor(gkBox));
            DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        genderCol.setCellRenderer(renderer);
            
            
            
            scrollPane = new JScrollPane(table);
            table.setPreferredScrollableViewportSize(new Dimension(1400, 400));
            JTableHeader header = table.getTableHeader();
            header.setBackground(Color.yellow);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            table.setAutoCreateRowSorter(true);
            table.setRowSelectionAllowed(true);
            table.setColumnSelectionAllowed(true);
            textArea = new JTextArea();
            scroll = new JPanel();
            scroll.add(scrollPane,BorderLayout.PAGE_START);
            scroll.add(textArea,BorderLayout.LINE_START);
           
             
        
                          
            for(int index = 1; index == 27; index++)
        {
        TableColumn col = table.getColumnModel().getColumn(index);
        int width = 150;
        col.setPreferredWidth(width);
        

        }
        int index0 = 0;
        TableColumn col = table.getColumnModel().getColumn(index0);
        int width = 250;
        col.setPreferredWidth(width);
        
    }
   
           
        
private class ComboBoxListener implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
String selection =(String) gkBox.getSelectedItem();

}
}
         
        private void jButton()
{
    buttonpanel = new JPanel();
    button = new JButton("Save selected to .txt");
    button1 = new JButton("hit to copy");
    button.setMnemonic(KeyEvent.VK_C);
    buttonpanel.add(button);
    buttonpanel.add(button1);
    buttonpanel.setSize(50,20);
    button.addActionListener(new ValueButtonListener());
    buttonpanel.setBackground(Color.DARK_GRAY);
}
    
    
    private class MyTableModel extends AbstractTableModel {
        
       
        private String[] columnNames = {"Name" , "Age", "Pos", "Nat", "St", "Tk", "Ps", "Sh", "Ag", "Kab", "Tab", "Pab", "Sab", "Gam", "Sub", "Min", "Mom", "Sav", "Con", "Ktk", "Kps", "Sht", "Gls", "Ass", "DP", "Inj", "Sus", "hi"};
        

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return rosterList.size();
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

      
        public Object getValueAt(int row, int col) 
        
               { 
               return rosterList.get(row)[col];
               
               }
               
                 
                           
               public boolean isCellEditable(int row,int col)
               {
                   return true;
               }
               
       public void setValueAt(Object value, int row, int col) {
        value = rosterList.get(row)[col];
        fireTableCellUpdated(row, col);
    }
                     
                                                      
    } 


        
    
    
    private void textRead() 
  {
      
     
     
     try
    {
      yahoo = new URL("http://www.afterextratime.net/game/spa/Ars.txt");
        URLConnection yc = yahoo.openConnection();
        BufferedReader br = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String line = br.readLine();                        
        
      while (line != null )
      {
        String [] rowfields = line.split("[ ]+");
        String[] columnData =  Arrays.copyOf(rowfields, rowfields.length + 1);
        rosterList.add(columnData);
        
        line = br.readLine();
       }
     
    }
    catch (FileNotFoundException e)
    {
      // can be thrown when creating the FileReader/BufferedReader
      // deal with the exception
      e.printStackTrace();
    }
    catch (IOException e)
    {
      // can be thrown by br.readLine()
      // deal with the exception
      e.printStackTrace();
    }
        
}


 private class ValueButtonListener implements ActionListener{
            
             public void actionPerformed (ActionEvent event){
         
                 
    int[] selectedRows= table.getSelectedRows();
    int[] selectedColumns = table.getSelectedColumns();
      String space = "\n";
      
       
    
   for (int p = 0; p < selectedRows.length; p++) {
     selectedRows[p] = table.convertRowIndexToModel(selectedRows[p]);
   }

        try {
                  PrintWriter pw = new PrintWriter("RostersSAVED.txt");
                 
                  
                
                     
      
      for(int i=0;i<selectedRows.length ;i++ )
      {
          
          String name = rosterList.get(selectedRows[i])[selectedColumns[0]]; 
          String padName0 = name+"               ";
          String fixedlength = padName0.substring(0,14);
          pw.print( fixedlength);
          pw.print(rosterList.get(selectedRows[i])[selectedColumns[1]]);
          
          for(int j = 2; j<4; j++)
            {
            int len = rosterList.get(selectedRows[i])[selectedColumns[j]].length();
            String name1 = rosterList.get(selectedRows[i])[selectedColumns[j]]; 
            String padName1 = "     "+name1;
            String fixedlength1 = padName1.substring(len+1, len+5);
            pw.print(fixedlength1);
                                         
            }
            
              for(int k = 4; k<9; k++)
            {
            int len1 = rosterList.get(selectedRows[i])[selectedColumns[k]].length();
            String name2 = rosterList.get(selectedRows[i])[selectedColumns[k]]; 
            String padName2 = "  "+name2;
            String fixedlength2 = padName2.substring(len1-1);
            pw.print(fixedlength2);
                                         
            }
            
               for(int l = 9; l < 15; l++)
            {
            int len2 = rosterList.get(selectedRows[i])[selectedColumns[l]].length();
            String name3 = rosterList.get(selectedRows[i])[selectedColumns[l]]; 
            String padName3 = "    "+name3;
            String fixedlength3 = padName3.substring(len2);
            pw.print(fixedlength3);
                                         
            }
            
               for(int m = 15; m < 16; m++)
            {
            int len3 = rosterList.get(selectedRows[i])[selectedColumns[m]].length();
            String name4 = rosterList.get(selectedRows[i])[selectedColumns[m]]; 
            String padName4 = "    "+name4;
            String fixedlength4 = padName4.substring(len3-1);
            pw.print(fixedlength4);
                                         
            }
            
                for(int t = 16; t < 27; t++)
            {
            int len4 = rosterList.get(selectedRows[i])[selectedColumns[t]].length();
            String name5 = rosterList.get(selectedRows[i])[selectedColumns[t]]; 
            String padName5 = "   "+name5;
            String fixedlength5 = padName5.substring(len4-1);
            pw.print(fixedlength5+"\n");
                                        
            }
            
            
            
            pw.println(space);                        
        }    
           
    pw.close(); 
       }catch (IOException e) {
                }
      
    
            
  }
    
    
}    
}

"setValueAt()" needs to set that value in your rosterList data, so it should be

public void setValueAt(Object value, int row, int col) {
    if (value != null) {
        rosterList.get(row)[col] = String.valueOf(value);
        fireTableCellUpdated(row, col);
    }
}

The null check prevents if from putting the word "null" in the cell if you select the combobox cell but do not select a value.

Edit: I also forgot to mention that this loop for(int index = 1; index == 27; index++) will never execute because 1 != 27 on the first check. I think you meant index < 27;

i have a JTextArea undearneath my JTable.. and now have created a new JPanel with JRadiobuttons on it... what i want to do now is when i select a JRadioButton to print the value that i have assigned to it in the JTextArea on row 2... and if the user changes there selection in the JRadiobuttons then to update the value on row 2..

here is a pic:
http://img148.imageshack.us/img148/4167/rostersorter.jpg

the radio buttons have strings assigned to them of one character... so if u select button A then it should print "A" in the JTextArea, i want it printed under laz... and always to be there when selected a radio button.

i can get it to print there but it doesnt update when i select another one... just keeps adding on.

help please :(

Which method are you using?
There is the JTextArea.append and the JTextArea.setText.
I believe you understand what they do.
It is always best to check the API when you don't know why something doesn't work

im using the append method.. but it doesnt update... just keeps adding on everytime i select a radio button
i then tried the replaceRange method from the API... which does work, it updates but it only does it on the first line (replaces the first letter in laz)... can't get it to move down to the second line and leave "laz" in place.

You have already mentioned the append method. But I mentioned the setText method. Maybe you should give it a try.
Try getting the text, modify it and then use the setText

ive already tried the setText method for one word, it does the same thing... are you saying i should first collect the words that are going to be entered, organise them the way i want and then use setText on the whole lot?

Well you have seen what append does and what setText does. If I remember correctly the setText simply sets the entire text of the Area with the input argument.
So it's up to you how to proceed.

If you want to get the entire String text from the Area, you might want to use the split method of the String class in order to separate the lines:

String [] arrayLines = area.getText().split("\n");

the column index starts from 0
therefore you should type 26 instead of 27
that simple

Seriously? You resurrected this 2-year-old thread to post that? Did you even bother to read the rest of the posts?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.