Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: JTable Questions

  1. #1
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default JTable Questions

    I have a few questions related to JTables so bear with me and if you could answer what you know, it would be appriecated.

    My GUI has a few components, but 2 main ones.
    1. A JList of "Chart" Objects. A "Chart" Object contains String Data Range, String Title, String Left Axis Label, String Bottom Axis Label, String Type, and ArrayList<SeriesInfo> list of series. (Those are obviously not their variable names). A "SeriesInfo" Object contains String Name, Point Start, Point End, String DataLabel, String DataRange, Color SeriesColor, and boolean PrimaryAxis.
    2. A JTable with 5 columns. The data for those columns are, 1) String, 2) String, 3) CheckBox, 4) Color Picker/Background Colored, 5) String.

    Apart from those, there are 3 JToggleButtons and 3 JTextFields.

    How this is going to work is that when the user selects a Chart from the JList, it will update the 3 JToggleButtons, 3 JTextFields, and the JTable. The content of the JTable will be the Chart Object's SeriesInfo objects. So when the user selects a Chart from the JList, the JTable will need to dynamically change row count and add new data. The columns will get their data from the following: 1) SeriesInfo.Name, 2) SeriesInfo.DataRange, 3) SeriesInfo.PrimaryAxis, 4) SeriesInfo.SeriesColor, 5) SeriesInfo.DataLabel.

    So, now that you are familiar with my design, here are my JTable questions:
    1. How can I make the size of the JTable dynamically? The number of the Rows of the JTable will depend on the the length of the SeriesInfo ArrayList of the Chart Object. My current design makes a statically sized JTable.
    2. How can I make the boolean CheckBox an actual CheckBox? At first I just had the true/false value, then I played around on Google and got the CheckBox to show instead of the text, but when you click in the CheckBox is just turns back into text and I get a bunch of errors about parsing the String when you try to click out of it.
    3. How can I open a Color Picker Pop-up when the user clicks in a cell in the 4th column? I assume I need an ActionListener of some sorts, but I'm not sure where to go with it.

    I think thats everything, I will continue to ask questions as I go.

    My current JTable code (which I got from playing around on Google and trying things out will need some major overhaul) is this:
    String[] columnNames = {"Data Name",
                                    "Data Range",
                                    "Primary Axis",
                                    "Color",
                                    "Data Label"};
     
            Object[][] data = {
    	    {"DataName", "A3:A25",
    	     new Boolean(false), "Color Picker", "Label"}
            };
     
            final JTable table = new JTable(data, columnNames);
     
            table.getColumnModel().getColumn(2).setCellRenderer(new TableCellRenderer()
            	{
                	public Component getTableCellRendererComponent(
    					JTable table, Object value, boolean isSelected,boolean isFocused, int row, int col)
    					{
    						boolean marked = (Boolean) value;
    						JCheckBox rendererComponent = new JCheckBox();
    						if (marked)
    						{
    							rendererComponent.setSelected(true);
    						}
    						return rendererComponent;
    					}
    			});
     
            JScrollPane tableScroller = new JScrollPane(table);
    		tableScroller.setPreferredSize(new Dimension(400, 70));


  2. #2
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,104
    Thanks
    169
    Thanked 780 Times in 726 Posts
    Blog Entries
    5

    Default Re: JTable Questions

    Quote Originally Posted by aussiemcgr View Post

    So, now that you are familiar with my design, here are my JTable questions:
    1. How can I make the size of the JTable dynamically? The number of the Rows of the JTable will depend on the the length of the SeriesInfo ArrayList of the Chart Object. My current design makes a statically sized JTable.
    2. How can I make the boolean CheckBox an actual CheckBox? At first I just had the true/false value, then I played around on Google and got the CheckBox to show instead of the text, but when you click in the CheckBox is just turns back into text and I get a bunch of errors about parsing the String when you try to click out of it.
    3. How can I open a Color Picker Pop-up when the user clicks in a cell in the 4th column? I assume I need an ActionListener of some sorts, but I'm not sure where to go with it.
    Create a custom TableModel (extend AbstractTableModel or DefaultTableModel) and set the table model to this custom model. Using the custom model will allow you to change the table quite dynamically (see How to Use Tables). Adding a ListSelectionListener to the ListSelectionModel will allow you to listen for selection in the table.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Ok, I could use some help as I go. I have never used TableModels, Table Rendering, or Vectors before.

    Vector Question:
    How do I go about making 2d Vectors, or is it necessary, or how exactly does this work?

    TableModel Question:
    In the code from above, it had something to do with Table Rendering. Is that done in the TableModel, or where do I do that?


    So based on that Java Tutorials site (in which I think they did a crap job explaining how JTables work), I have attempted to create a makeshift TableModel. How is this looking?:
    public class TableModel extends DefaultTableModel
    	{
    		Vector data;
    		Vector columns;
     
    		public TableModel(Vector dataV,Vector columnNames)
    		{
    			super(dataV,columnNames);
    			data = dataV;
    			columns = columnNames;
    		}
    		public int getColumnCount()
    		{
    			return columns.size();
    		}
    		public int getRowCount()
    		{
    			return data.size();
    		}
    		public String getColumnName(int col)
    		{
    			return columns.get(col).toString();
    		}
     
    	}

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Ok, so i have currently been able to Dynamically change the number of rows. So that is checked off.

    I still need help with:
    1. Setting selectable JCheckBox in JTable
    2. Opening Color Picker
    3. Setting Specific Cell Background Colors (for only the cells with Color Pickers on them).

    Any suggestions is apprieciated.

  5. #5
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,104
    Thanks
    169
    Thanked 780 Times in 726 Posts
    Blog Entries
    5

    Default Re: JTable Questions

    Quote Originally Posted by aussiemcgr View Post
    Ok, so i have currently been able to Dynamically change the number of rows. So that is checked off.

    I still need help with:
    1. Setting selectable JCheckBox in JTable
    2. Opening Color Picker
    3. Setting Specific Cell Background Colors (for only the cells with Color Pickers on them).

    Any suggestions is apprieciated.
    Tables aren't extremely intuitive until you start using them quite a bit.
    You may wish to change your model TableMode to avoid naming conflictsl, since (indirectly) it is implementing TableModel.

    1) By default checkboxes should appear with a boolean, but I've noticed some buggy looking behavior myself when relying on this. I can't recall exactly how I overcame this, but you may want to try returning the column class in your table model
    @Override public Class getColumnClass(int column){
        if ( column == 0 ){//or whichever column
            return Boolean.class;
       }
       return super.getColumnClass(column);
    }

    2) You could implement an action listener
    public void actionPerformed(ActionEvent e){
        int row = table.rowAtPoint(e.getPoint());
         int col = table.colAtPoint(e.getPoint());
    }
    This will return the row and column where the mouse click occurred. Alternatively you may wish to show a JPopUpMenu containing the Color chooser based upon the point location

    3) You could implement the TableCellRenderer interface, and override the getCellRenderer function of JTable, returning the custom renderer when needed, and the default (super) renderer otherwise

  6. #6
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    489
    Thanks
    8
    Thanked 45 Times in 43 Posts

    Default Re: JTable Questions

    ActionEvent doesn't have a getPoint() method. You probably meant to illustrate that with a MouseListener and mousePressed(...) or mouseClicked(...)

    db

  7. #7
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,104
    Thanks
    169
    Thanked 780 Times in 726 Posts
    Blog Entries
    5

    Default Re: JTable Questions

    Quote Originally Posted by Darryl.Burke View Post
    ActionEvent doesn't have a getPoint() method. You probably meant to illustrate that with a MouseListener and mousePressed(...) or mouseClicked(...)

    db
    Doh! Thanks for the correction. My brain is running on low today

  8. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Tables aren't extremely intuitive until you start using them quite a bit.
    You may wish to change your model TableMode to avoid naming conflictsl, since (indirectly) it is implementing TableModel.
    I actually just used the DefaultTableModel to do what I needed. However I know I'm going to have to create a new Table Model class to get done what I need, and I'm trying to put that off as long as possible.

    MouseListener and mousePressed(...) or mouseClicked(...)
    Ok, so I am not able attach a listener to a specific cell? If possible, some sort of Cell Selection Listener would be best. I am having trouble finding anything like this on Google though.

    3) You could implement the TableCellRenderer interface, and override the getCellRenderer function of JTable, returning the custom renderer when needed, and the default (super) renderer otherwise
    I'll spend some time playing around with Table Rendering tomorrow at work and get back to you as I run into the inevitable problems.



    I also have 1 question about the JList thing. I have attached a listener to react when an item is selected, but it seems to run the listener twice when it activates. This was a problem initially because it attempted to update the TableModel when one had not yet been created (which threw NullPointers at me like crazy) but a few if statements made a messy fix for that. Any suggestions regarding adding Listeners to JLists?

  9. #9
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    489
    Thanks
    8
    Thanked 45 Times in 43 Posts

    Default Re: JTable Questions

    Quote Originally Posted by aussiemcgr View Post
    Ok, so I am not able attach a listener to a specific cell? If possible, some sort of Cell Selection Listener would be best. I am having trouble finding anything like this on Google though.
    Check out Rob Camick's Table Cell Listener, it may be what you're looking for.

    db

  10. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Ok, so it can listen for when I change a value, but it doesnt listen for when the cell is selected.

    So I played around with creating a TableColumnModelListener instead:
        public class TableSelectionListener implements TableColumnModelListener
        {
        	public void columnAdded(TableColumnModelEvent e)
        	{  	}
        	public void columnMarginChanged(ChangeEvent e)
        	{  	}
     		public void columnMoved(TableColumnModelEvent e)
     		{	}
     		public void columnRemoved(TableColumnModelEvent e)
     		{	}
        	public void columnSelectionChanged(ListSelectionEvent e)
        	{
        		System.out.println(table.getSelectedRow()+","+table.getSelectedColumn());
        	}
        }

    And adding it to my table:
    		TableColumnModelListener colListener = new TableSelectionListener();
    		table.getColumnModel().addColumnModelListener(colListener);

    But there is a problem. Just like with the JList, it runs the listener twice. Except this time, I get two different answers. When I click the top left cell, this prints out:
    -1,0
    0,0
    When I click the bottom left cell, this prints out:
    1,0
    1,0
    When I click the top right cell, this prints out:
    1,4
    0,4
    When I click the bottom right cell, this prints out:
    1,4
    1,4
    It does print out the correct answer for the bottom cells, except it does it twice. But I dont know what is going on for the top cells. Lastly, it doesnt appear to be reliable. Sometimes it responds, sometimes it doesnt.
    Last edited by aussiemcgr; July 30th, 2010 at 08:41 AM.

  11. #11
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,104
    Thanks
    169
    Thanked 780 Times in 726 Posts
    Blog Entries
    5

    Default Re: JTable Questions

    Quote Originally Posted by aussiemcgr View Post
    Ok, so it can listen for when I change a value, but it doesnt listen for when the cell is selected.
    If you just need to listen for selection events, register a ListSelectionListener on the table's selection model.

  12. #12
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Ok, so I've pretty much got what I wanted (with a few bugs left that need to be found).

    I do have a question still related to the project, but not so much JLists or JTables. This is a form that the user opens with a button from the main window. When this window is created, it is sent an ArrayList<ChartInfo> object that contains all of the automatically gotten chart information prior to opening the window. This window edits that array. How can I return the array back to the main class? Since it is all listeners and whatnot, there are no real methods, except for the contructor (which I cant return stuff from, correct?). Specifically, I need to return the arraylist when the frame is closed.

  13. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Also, in my ListSelectionListener, I am also attempting to change the values of my Checkboxes, but it doesnt work correctly.

    	public class TableSelectionListener implements ListSelectionListener
    	{
    		public void valueChanged(ListSelectionEvent e)
    		{
    			if(!e.getValueIsAdjusting())
    			{
    				if(table.getSelectedColumn()==3)
    				{
    					int row = table.getSelectedRow();
    					int tempNum = list.getSelectedIndex();
    					JColorChooser colorChooser = new JColorChooser();
    					Color colour = colorChooser.showDialog(panel,"Series Color",(Color)table.getValueAt(row,3));
    					//Color colour = colorChooser.getColor();
    					System.out.println(colour);
    					chartArray.get(tempNum).series.get(row).color = colour;
    					list.setListData(new Vector(chartArray));
    					list.setSelectedIndex(tempNum);
    					table.setValueAt(colour,row,3);
    					list.setSelectedIndex(tempNum);
    				}
    				else if(table.getSelectedColumn()==2)
    				{
    					int row = table.getSelectedRow();
    					int tempNum = list.getSelectedIndex();
    					System.out.println(row);
    					boolean tempBol = (Boolean)table.getValueAt(row,2);
    					System.out.println(tempBol);
    					chartArray.get(tempNum).series.get(row).primeAxis = tempBol;
    					list.setListData(new Vector(chartArray));
    					list.setSelectedIndex(tempNum);
    					table.setValueAt(!tempBol,row,2);
    					list.setSelectedIndex(tempNum);
    				}
    			}
    		}
    	}

    The else if(table.getSelectedColumn()==2) statement starts the Checkbox part. The value is being set correctly initially, but the values are not always being kept correct when I move onto the next JTable.

    All Checkbox values are by default set to true. When I click the cell, it sets it to false. When I move to the next JTable and then go back, the value is set back to true. If I double-click the cell, which sets it to false then true really quick AND breifly displays the text (true/false) and then leave the cell and come back to it, it has then set it to false. It would seem that my listener is only firing for my boolean when I double-click the cell. It is working fine for the Color Picker however, so I dont know what to make of this. I assume it has something to do with the Checkbox, but I dont entirely understand what I did wrong.

  14. #14
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    I am not also having an issue with another JTable where the ListSelectionListener (closely resembling the one above) seems to be removing itself after 1 usage, or at least not responding anymore. What could cause that?

    This issue solved, needed to include: patterns.changeSelection(row,col,true,false); to deselect cells.

    I am still having issues with my other questions though.
    Last edited by aussiemcgr; July 30th, 2010 at 02:30 PM.

  15. #15
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,104
    Thanks
    169
    Thanked 780 Times in 726 Posts
    Blog Entries
    5

    Default Re: JTable Questions

    First tip: when you call getSelectedRow() on a JTable, its always good practice to make sure it does not return -1 (if nothing is returned), otherwise when your code continues an exception may be thrown.

    Second, RE editing the cell values: in your DefaultTableModel, did you override the setValueAt()? This is necessary to change the data in memory.

  16. #16
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Well, I thought that my call to chartArray.get(tempNum).series.get(row).primeAxis = tempBol; would be setting it in memory, seeing how every time I change the JTable it regets the series information.

  17. #17
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Ok, I'm having alot of trouble with Table Selections.

    1. I need to select individual cells, but it would seem that it only records on row selections. Which means that if I attempt to select a different cell in the row, the valueChanged method doesnt get fired. I tried to work around this by saying patterns.changeSelection(row,col,true,false);, but this makes it so I am unable to select a cell and keep it selected. Surely there has to be a way to restrict only a cell to be selected and not the entire row to be considered selected. Initial thoughts would be to somehow allow the JTabel to only select 1 column in each row and 1 row in each column.

    2. When I remove the code: patterns.changeSelection(row,col,true,false); so a row is selected, and later attempt to remove the selected row using the code:
    if(patterns.getSelectedRow()!=-1)
    	model.removeRow(patterns.getSelectedRow());
    I somehow get an java.lang.ArrayIndexOutOfBoundsException: -1, which doesnt seem to make any sense since I checked for that prior to making the call...

  18. #18
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    489
    Thanks
    8
    Thanked 45 Times in 43 Posts

    Default Re: JTable Questions

    > Surely there has to be a way to restrict only a cell to be selected and not the entire row to be considered selected.
    setColumnSelectionAllowed(true)
    Really, you have to learn to search and read the API. Granted that the API for JTable has a *lot* of methods, but that's all the more reason for spending a *lot* of time to get familiar with it.

    You can also add a ListSelectionListener to the JTable's TableColumnModel's ListSelectionModel.

    db

  19. #19
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Quote Originally Posted by Darryl.Burke View Post
    > Surely there has to be a way to restrict only a cell to be selected and not the entire row to be considered selected.
    setColumnSelectionAllowed(true)
    Really, you have to learn to search and read the API. Granted that the API for JTable has a *lot* of methods, but that's all the more reason for spending a *lot* of time to get familiar with it.

    You can also add a ListSelectionListener to the JTable's TableColumnModel's ListSelectionModel.

    db
    I've attempted this already. All it does is make columns selectable, but it doesnt restrict it to only 1 column. AND, I currently have a ListSelectionListener added to the JTable, but my issue is that it selects the ENTIRE row when I make a selection, so when i attempt to make another selection in that row, it doesnt fire the ListSelectionListener because the selection has not changed.

  20. #20
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,104
    Thanks
    169
    Thanked 780 Times in 726 Posts
    Blog Entries
    5

    Default Re: JTable Questions

    table.setCellSelectionEnabled(true);

    To allow cell selections. The adding a ListSelectionListener to the SelectionModel will only fire upon row selection. If you add a ListSelectionListener on the SelectionModel of the ColumnModel of the table
    table.getColumnModel().getSelectionModel() .addListSelectionListener(...)
    will fire when the column gets changed. Both together will allow you to listen for different selections, however both together will get it to fire twice should both the row and column change.

  21. #21
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 300 Times in 282 Posts

    Default Re: JTable Questions

    Ok, so does the ListSelectionEvent.getValueIsAdjusting() method return true if the row change is begin listened to or the column change is being listened to, or am I still completely confused by this?

    This is the ListSelectionListener I have attempted to use. All it should do is open up a JColorChooser when I select a cell in either column index 1 or column index 2. Most of the time, the JTable will only have 1 row, but the user has the option to add more.
    Problems:
    1. This works first go, but valueChanged is never fired again unless I add a row and change rows.
    2. A JColorChooser is fired the number of times of rows per cell clicked. I just want it to fire once, regardless of the number of rows.

         public class TableSelectionListener implements ListSelectionListener
    	{
    		public void valueChanged(ListSelectionEvent e)
    		{
    			System.out.println(e);
    			if(!e.getValueIsAdjusting())
    			{
    				System.out.println(e.toString());
    				if(patterns.getSelectedColumn()==1 || patterns.getSelectedColumn()==2)
    				{
    					int row = patterns.getSelectedRow();
    					int col = patterns.getSelectedColumn();
    					JColorChooser colorChooser = new JColorChooser();
    					Color colour = colorChooser.showDialog(panel,"Series Color "+col,(Color)patterns.getValueAt(row,col));
    					System.out.println(colour);
    					patterns.setValueAt(colour,row,col);
    					patternData[row][col] = colour;
    				}
    			}
    		}
    	}

    This thing has been plaguing me for like 3 days now. Can anyone tell me what I'm doing wrong?

  22. #22
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    489
    Thanks
    8
    Thanked 45 Times in 43 Posts

    Default Re: JTable Questions

    A JTable has TWO associated list selection models.

    The table's selection model is concerned with row selection
    The table's column model's selection model is concerned with column selection
    To restrict a selection model to allow only a single selection you have to set its selection mode

    I think you can take it from there.

    db

Similar Threads

  1. A few questions
    By adenverd in forum Java Theory & Questions
    Replies: 3
    Last Post: May 26th, 2010, 03:34 AM
  2. [SOLVED] Some serious questions,
    By Time in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 17th, 2010, 02:52 AM
  3. [SOLVED] Questions About Threads
    By neo_2010 in forum Threads
    Replies: 4
    Last Post: March 15th, 2010, 09:04 AM
  4. Java Questions! :)
    By xs4rdx in forum Java Theory & Questions
    Replies: 0
    Last Post: February 21st, 2010, 07:40 AM
  5. Some basic questions.
    By trips in forum Java Theory & Questions
    Replies: 5
    Last Post: July 21st, 2009, 02:15 AM