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 23 of 23

Thread: JTable custom model listener

  1. #1
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default JTable custom model listener

    Hello, I created a default JTable and added a listener to it. Everything worked great. But the default model wasn't good enought, so I created my own. And once I change data nothing happens.

    My model class:
    package lslife.view;
     
    import javax.swing.table.AbstractTableModel;
     
    public class BanListTableModel extends AbstractTableModel {
     
    	private Object[][] data;
    	private String[] columnNames;
     
    	public BanListTableModel(Object[][] data,String[] columnames) {
    		this.data = data;
    		this.columnNames = columnames;
    	}
    	@Override
    	public int getRowCount() {
    		return data.length;
    	}
    	@Override
    	public int getColumnCount() {
    		return columnNames.length;
    	}
    	@Override
    	public String getColumnName(int column) {
    		return columnNames[column];
    	}
    	@Override
    	public void setValueAt(Object aValue, int rowIndex,int columnIndex) {
    		data[rowIndex][columnIndex] = aValue;
    	}
    	@Override
    	public Object getValueAt(int rowIndex, int columnIndex) {
    		return data[rowIndex][columnIndex];
    	}
    	@Override 
    	public boolean isCellEditable(int rowIndex,int columnIndex) {
    		if(columnIndex == 0 || columnIndex == 4) return false;
    		return true;
    	}
     
     
    }


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    I created a default JTable and added a listener to it. Everything worked great. But the default model wasn't good enought
    First, just for clarity: you are speaking about a "listener". A table model is not a listener.
    It depends on what table model you have used. If you have used the constructor JTable(Object[][] rowData, Object[] columnNames), it uses an implicit-internal table model. But there is also the class DefaultTableModel.

    Quote Originally Posted by Bebras View Post
    so I created my own.
    Conceptually, your table model is not much better than the implicit table model into JTable or the DefaultTableModel. Your table model is still "generical" and unstructured, without any notion of the "entity" represented by each row.

    The only "new" thing is that now, being developed by you, the table model can control the editability of cells.

    Quote Originally Posted by Bebras View Post
    And once I change data nothing happens.
    Your table model is quite correct. It "exposes" all the informations in the right way. But the setValueAt is not completely correct. It's necessary to change the internal data structure (obviously) but not sufficient. You have to "fire" the appropriate event so that JTable (and any other registered TableModelListener) can known that "something" is changed (for JTable it means: update the view).

    So, in setValueAt use also the fireTableCellUpdated(int row, int column) to send this notification.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  3. The Following User Says Thank You to andbin For This Useful Post:

    Bebras (January 12th, 2014)

  4. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JTable custom model listener

    I would recommend extending DefaultTableModel, not AbstractTableModel. The reason being is that DefaultTableModel would have existing functionality which you may have overlooked. It is more of a simplification technique than a requirement. Extending AbstractTableModel should be fine. I'm just giving my two cents.

    Are you changing data by editing the table directly? If so, I don't know if the model data is changed by default. You might need to add a listener to the table and manually trigger the update or something.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Bebras (January 12th, 2014)

  6. #4
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    new problem!
    I also wanted to add a button as a cell, so I created a "TableButton" class which extends JButton and implements TableCellEditor AND TableCellRenderer.
    All is great except that I want everything but the button to be non-editable, I know that I need to define this in the table model class:
    @Override 
    	public boolean isCellEditable(int rowIndex,int columnIndex) {
    		if(columnIndex == 7) return true;
    		return false;
    	}

    But this code does not work. Nothing is "editable" meaning I can't click the button.(100% the index is correct), but if i always return true, then it works(but other cells ar editable, which is something i don't want)

  7. #5
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    But this code does not work. Nothing is "editable" meaning I can't click the button.(100% the index is correct), but if i always return true, then it works(but other cells ar editable, which is something i don't want)
    A false from isCellEditable means primarily one thing: that the table cell editor never become "active".

    So you want button column editable and all other columns non-editable, right? And then your last code is .... conceptually correct!
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  8. #6
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    Yes that is right. Why do you say "conceptually"? How it isn't correct?

  9. #7
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    Yes that is right. Why do you say "conceptually"? How it isn't correct?
    The concept "if it's the buttons column, return true otherwise return false" is correct. But technically, is 7 the column index of buttons? Are you sure?
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  10. #8
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    5f6p.jpg
    Just to be sure.

  11. #9
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    Just to be sure.
    Yes, for what I see it's the eighth column, that is index 7 (being 0-based). And what happens? Is the button clickable or not?

    P.S. do you have hidden/zero-width columns?
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  12. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JTable custom model listener

    Just as an exercise in testing andbin's theory, tell me if this changes the result:
    @Override 
    	public boolean isCellEditable(int rowIndex,int columnIndex) {
    		if(columnIndex == getColumnCount()-1) return true;
    		return false;
    	}
    In the final code, you would probably want hardcoded column numbers (unless you intend the last column to always be the button, I suppose, but hardcoded for this scenario would probably be best since it would reduce complexity).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  13. #11
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    No. The button is still not selectable.
    JTable list = new JTable();
    		list.setModel(new BanListTableModel(data,columnames));
    		TableButton button = new TableButton("Atbaninti");
    		button.addTableButtonListener(new TableButtonListener() {
    			public void tableButtonClicked(int row,int col) {
    				System.out.println("Button click");
    			}
    		});
    		TableColumn col = new TableColumn();
    		col.setCellRenderer(button);
    		col.setCellEditor(button);
    		col.setHeaderValue("Veiksmas");
    		list.addColumn(col);
    		list.getModel().addTableModelListener(tableListener);

    Maybe it's because I add the button cell AFTER I set the model?
    But if I change it the other way around it doesn't work at all.

  14. #12
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JTable custom model listener

    Ok. Wait, so if you set the table to be fully editable, are you 100% the button works?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  15. #13
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    Yes. The text "Button clicked" is printed

  16. #14
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JTable custom model listener

    With your current setup (with only column 7 enabled), add this to the end of your code:
    System.out.println(list.isCellEditable(0,7)+"");
    System.out.println(list.getModel().isCellEditable(0,7)+"");
    And tell us what the results are.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  17. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Bebras (January 15th, 2014)

  18. #15
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    		TableColumn col = new TableColumn();
    		col.setCellRenderer(button);
    		col.setCellEditor(button);
    		col.setHeaderValue("Veiksmas");
    		list.addColumn(col);
    Wait! You are adding an explicit column! And a TableColumn has the 'modelIndex' property (getModelIndex/setModelIndex methods) that you have not configured, thus it's 0. In other words: when isCellEditable is invoked for the added column, the column parameter is 0.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  19. The Following User Says Thank You to andbin For This Useful Post:

    Bebras (January 15th, 2014)

  20. #16
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    Okay. So I used the setModelIndex method and got an array index out of bounds exception.

    JTable has a construtor JTable(int numRows, int numColumns), so I set tthe number of colums to the size of my columnames array + 1. Same exception.

    I set its model to my custom one. It also has a method "getColumnCount", so I added number of colums to its constructor.. Same exception.

    Where should I set the number of colums for a JTable?

  21. #17
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    and got an array index out of bounds exception.
    Where? I suspect in the getValueAt of your BanListTableModel.
    Describe (or post) your BanListTableModel.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  22. The Following User Says Thank You to andbin For This Useful Post:

    Bebras (January 15th, 2014)

  23. #18
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    You are right. Should I just check if it is a valid index? But somehow that doesn't sound correct. What value does it have to return for a button? Because I just return an element from the array passed in at the constructor with indexes passed into the method.

  24. #19
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    Should I just check if it is a valid index? But somehow that doesn't sound correct. What value does it have to return for a button?
    The value from getValueAt is, at the end, simply passed to the renderer. If your button-renderer doesn't care about the value, you can return null, "", anything you want.

    Imagine another scenario, for example, where you want to have different texts for each button. Here you would need a button-renderer that cares about the value, and set it to the button. And all texts would be "exposed" by the table model.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  25. The Following User Says Thank You to andbin For This Useful Post:

    Bebras (January 15th, 2014)

  26. #20
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    Well but my button renderer does return "",
    @Override
    	public Object getCellEditorValue() {
    		return "";
    	}
    Your scenario sounds great and I'm pretty sure I'll want to add more buttons with different texts. So following this scenario I should keep the button text stored(a private instance variable) and return that ?

    This is my models getValueAt:
    @Override
    	public Object getValueAt(int rowIndex, int columnIndex) {
    		return data[rowIndex][columnIndex];
    	}
    How do I get the value from my button renderer to return here?

  27. #21
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    Your scenario sounds great and I'm pretty sure I'll want to add more buttons with different texts. So following this scenario I should keep the button text stored(a private instance variable) and return that ?
    The first important thing is that your getValueAt must return the button text when requested for the row/column of a button. How you decide what text to return is a "strategy" that involves only the internal logic of the table model. You can have the text stored in the data array, or it can be decided basing on other values or other logic. All this is not important from an external point of view.

    The renderer receives the value as a parameter to the getTableCellRendererComponent method as an Object. You "know" that this object is a String, being for a button text. So every time you prepare the component (your button) to return, simply set also the text.
    Note that typically (to save on resources) the renderer is itself the component to return. So typically the returned component is always the same object, just prepared from time to time.

    For the editor is a similar story (see getTableCellEditorComponent of TableCellEditor).
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  28. The Following User Says Thank You to andbin For This Useful Post:

    Bebras (January 15th, 2014)

  29. #22
    Junior Member
    Join Date
    Jan 2014
    Posts
    20
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: JTable custom model listener

    Well first of all, I finally got it to work. Credits to you ofcourse.

    These "strategies" you were talking about ? Can you give me an example? Now I just set the button's text to the same text as text in data array.

  30. #23
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: JTable custom model listener

    Quote Originally Posted by Bebras View Post
    These "strategies" you were talking about ? Can you give me an example? Now I just set the button's text to the same text as text in data array.
    I mean, in general, that it's not always necessary to keep an entire column in the internal data structure of the model for these button texts. Imagine a table model for stock prices, where the internal data structure has some informations that you can use to deduce if the button text must be "Sell" or "Buy".
    Something like this ...

    The choice of the text can also be delegated to the renderer/editor. The table model could return an int or enum value and the renderer/editor can select the appropriate text. These are design choices, that doesn't change the final result.

    The important thing is that there must be an implicit "relation" between the renderer/editor and the value of the relative column in the model.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  31. The Following User Says Thank You to andbin For This Useful Post:

    Bebras (January 15th, 2014)

Similar Threads

  1. [SOLVED] Custom listener: how to separate interactors
    By Bebras in forum Java Theory & Questions
    Replies: 2
    Last Post: February 5th, 2014, 05:19 AM
  2. Design Model-Assignment
    By JavaStudent100 in forum What's Wrong With My Code?
    Replies: 12
    Last Post: August 28th, 2013, 08:01 PM
  3. Model View Controller help
    By kari4848 in forum AWT / Java Swing
    Replies: 2
    Last Post: November 15th, 2012, 03:19 PM
  4. Markov model
    By KobusJordaan in forum Algorithms & Recursion
    Replies: 1
    Last Post: October 19th, 2012, 09:06 PM
  5. Unstructured Data Model
    By richip in forum Object Oriented Programming
    Replies: 1
    Last Post: March 17th, 2011, 09:25 AM