473,406 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Changing the editability of a JTable cell through a TableModelEvent

blazedaces
284 100+
Hi guys, what I'm I have is a jtable with boolean variables in the first column and text in the next two (checkboxes). I want my tableChanged method to make it so when I check one of the checkboxes then it would change whether that third column is editable or not.

I have made a short[][] array that would hold values of either 0 or 1, basically whether or not each cell is editable or not. Along with that is obviously a setEditable(int row, int col, short editability) method. I think that part works well, it's simply the tableChanged method which I think I'm doing incorrectly.

My issue is this: is there a way to access the methods of an AbstractTableModel of a specific table? If I knew how to do that then it would be easy. Perhaps that is not the problem at all, I don't know.

Here's my code:

Expand|Select|Wrap|Line Numbers
  1. import java.awt.*;
  2. import javax.swing.*;
  3. import javax.swing.event.*;
  4. import javax.swing.table.AbstractTableModel;
  5. import java.util.*;
  6.  
  7. public class TagChoosingWindow extends JPanel implements TableModelListener {       
  8.        private JTable table;
  9.        private MyTableModel tableModel;  //Here's the model I'm using
  10.  
  11.     public TagChoosingWindow(ArrayList<String> al) {        
  12.         super(new GridLayout(1,0));
  13.  
  14.         tableModel = new MyTableModel(al);
  15.         table = new JTable(tableModel);
  16.         table.setPreferredScrollableViewportSize(new Dimension(500, 400));
  17.         table.setFillsViewportHeight(true);
  18.         table.setLocation(50, 50);
  19.  
  20.         //Create the scroll pane and add the table to it.
  21.         JScrollPane scrollPane = new JScrollPane(table);
  22.  
  23.         //Add the scroll pane to this panel.
  24.         add(scrollPane);
  25.     }
  26.  
  27.     public void tableChanged(TableModelEvent e) {
  28.         int row = e.getFirstRow();
  29.         int column = e.getColumn();
  30.         String columnName = tableModel.getColumnName(column);
  31.         Object data = tableModel.getValueAt(row, column);
  32.  
  33.         if (data.equals(Boolean.TRUE))
  34.             tableModel.setEditable(row, column, (short) 1);
  35.         else if(data.equals(Boolean.FALSE))
  36.             tableModel.setEditable(row, column, (short) 0);
  37.     }
  38.  
  39.     private static void createAndShowGUI(ArrayList<String> al) {
  40.         //Create and set up the window.
  41.         JFrame frame = new JFrame("TableDemo");
  42.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  43.  
  44.         //Create and set up the content pane.
  45.         TagChoosingWindow newContentPane = new TagChoosingWindow(al);
  46.         newContentPane.setOpaque(true); //content panes must be opaque
  47.         frame.setContentPane(newContentPane);
  48.  
  49.         //Display the window.
  50.         frame.pack();
  51.         frame.setVisible(true);
  52.     }
  53.  
  54.     public static void main(String args[]) {
  55.         //Schedule a job for the event-dispatching thread:
  56.         //creating and showing this application's GUI.
  57.         javax.swing.SwingUtilities.invokeLater(new Runnable() {
  58.             public void run() {
  59.                 ArrayList<String> temp = new ArrayList<String>(2);
  60.                 temp.add("First Tag\\");
  61.                 temp.add("Second Tag\\");
  62.                 createAndShowGUI(temp); 
  63.             }
  64.         });
  65.     }
  66.  
  67.     class MyTableModel extends AbstractTableModel {
  68.         private String[] columnNames = {"Which Data is Used",
  69.                                         "Original Tag Name",
  70.                                         "Name To Appear in NRDCBin Header File" };
  71.         private Object[][] data;
  72.         private short[][] editable;
  73.  
  74.         public MyTableModel(ArrayList<String> al) {
  75.             int size = al.size();
  76.             data = new Object[size][3];
  77.             editable = new short[size][3];
  78.  
  79.             for (int i = 0; i < size; i++) {
  80.                 data[i][0] = new Boolean(true);
  81.                 editable[i][0] = 1;
  82.  
  83.                 data[i][1] = al.get(i);
  84.                 editable[i][1] = 0;
  85.  
  86.                 data[i][2] = al.get(i);
  87.                 editable[i][2] = 1;
  88.             }
  89.         }
  90.  
  91.         public int getColumnCount() {
  92.             return columnNames.length;
  93.         }
  94.  
  95.         public int getRowCount() {
  96.             return data.length;
  97.         }
  98.  
  99.         public String getColumnName(int col) {
  100.             return columnNames[col];
  101.         }
  102.  
  103.         public Object getValueAt(int row, int col) {
  104.             return data[row][col];
  105.         }
  106.  
  107.         /*
  108.          * JTable uses this method to determine the default renderer/
  109.          * editor for each cell.  If we didn't implement this method,
  110.          * then the last column would contain text ("true"/"false"),
  111.          * rather than a check box.
  112.          */
  113.         public Class getColumnClass(int c) {
  114.             return getValueAt(0, c).getClass();
  115.         }
  116.  
  117.         public void setEditable(int row, int col, short editability) {
  118.             if (editability > 1 || editability < 0) {
  119.                 System.out.println("Editability is like a boolean, it should only hold the value of zero or one!");
  120.                 System.exit(1);
  121.             }
  122.             editable[row][col] = editability;
  123.         }
  124.  
  125.         /*
  126.          * Don't need to implement this method unless your table's
  127.          * editable.
  128.          */
  129.         public boolean isCellEditable(int row, int col) {
  130.             //Note that the data/cell address is constant,
  131.             //no matter where the cell appears onscreen.
  132.             if (editable[row][col] == 0)
  133.                 return false;
  134.             else
  135.                 return true;
  136.         }
  137.  
  138.         /*
  139.          * Don't need to implement this method unless your table's
  140.          * data can change.
  141.          */
  142.         public void setValueAt(Object value, int row, int col) {
  143.             data[row][col] = value;
  144.             fireTableCellUpdated(row, col);
  145.         }
  146.     }
  147. }
  148.  
And thank you so much for your time and your help.

-blazed
Jul 20 '07 #1
7 17173
JosAH
11,448 Expert 8TB
My issue is this: is there a way to access the methods of an AbstractTableModel of a specific table? If I knew how to do that then it would be easy. Perhaps that is not the problem at all, I don't know.
Have a look at the JTable.getModel() method; it returns the TableModel
being in use for that particular table. If you *know* the exact table model you
can even cast that TableModel return value to the implementation type you want.

kind regards,

Jos
Jul 20 '07 #2
blazedaces
284 100+
Have a look at the JTable.getModel() method; it returns the TableModel
being in use for that particular table. If you *know* the exact table model you
can even cast that TableModel return value to the implementation type you want.

kind regards,

Jos
Thank you very much for the help. I believe I did what you advised (I think), but it didn't work. Here's my tableChanged method now:

Expand|Select|Wrap|Line Numbers
  1.     public void tableChanged(TableModelEvent e) {
  2.         int row = e.getFirstRow();
  3.         int column = e.getColumn();
  4.         MyTableModel model = (MyTableModel)table.getModel();
  5.         String columnName = model.getColumnName(column);
  6.         Object data = model.getValueAt(row, column);
  7.  
  8.         if (data.equals(Boolean.TRUE))
  9.             model.setEditable(row, column, (short) 1);
  10.         else if(data.equals(Boolean.FALSE))
  11.             model.setEditable(row, column, (short) 0);
  12.     }
  13.  
I still think though that this way of doing it will never work. I think this is so because Java only passes everything by reference so the returned table model, even if I change some variable in it using setEditable it will only change the editable of the new model...

UNLESS I set the JTable to have a new table model...hmm? I don't know, just came to a realization. But won't that not work, the gui is running, what will that do to the table... I'll give it a wack anyways...

I will try, and thank you for your help.

-blazed
Jul 20 '07 #3
blazedaces
284 100+
Hold up, before you come and try to guide me that way, I think I have thought of a better solution... I should probably avoid the entire tableChanged method if I just change the isEditable method.

I should make it check what the values inside the checkBoxes are at the moment and that should return what value boolean they're holding... something like that.

Again, I'll be back in a few to update you guys. Thanks again for all your help,

-blazed
Jul 20 '07 #4
JosAH
11,448 Expert 8TB
I think this is so because Java only passes everything by reference
You don't want to be defenestrated do you?

kind regards,

Jos ;-)
Jul 20 '07 #5
blazedaces
284 100+
You don't want to be defenestrated do you?

kind regards,

Jos ;-)
Well... I ... I mean... it sounds fun to tell you the truth. Depends how high a window though, because if it's high enough I can pull out the parachute or glide (both of which fit in my left back pocket) but if it's only a few floors up, but too high to live through and no trees or big people to break my fall... I see things turning for the worse...

This was mentioned once amongst my friends and we all agreed it had to be the funniest word we had ever heard or could even possibly imagine ... as a word.

Anyway, here's my isEditable method and I'm certainly doing something wrong here, because I get an error message (I'll write it at the end):

Expand|Select|Wrap|Line Numbers
  1.         public boolean isCellEditable(int row, int col) {
  2.             //Note that the data/cell address is constant,
  3.             //no matter where the cell appears onscreen.
  4.             if (col == 1)
  5.                 return false;
  6.                else if (col == 0)
  7.                    return true;
  8.             else {
  9.                 return ((Boolean)(getValueAt(row, col)).booleanValue());
  10.             }
  11.         }
  12.  
The getValueAt returns the Object data[row][col] but I guess even though the Object returned is a Boolean things don't work out quite like I would like them to... does anyone know of a solution?

It says it doesn't recognize the .booleanValue() in that one line

Basically I want to get the Boolean value of those checkBoxes stored in the data[row][0] (the checkboxes are in the first column) and then use that to determine whether or not the cell is editable...

Thanks again for your help,

-blazed
Jul 20 '07 #6
blazedaces
284 100+
I made it work! But it helped to re-read my post, first I tried to just ask it if equaled a new Boolean(true), but then when re-reading I remembered, I'm asking for the value of data[row][col] but that value is a string, the Boolean values are at data[row][0], like I said in the post above, how foolish of me!

Don't know if it matters, but the working isEditable looked like this:

Expand|Select|Wrap|Line Numbers
  1.         public boolean isCellEditable(int row, int col) {
  2.             //Note that the data/cell address is constant,
  3.             //no matter where the cell appears onscreen.
  4.             if (col == 1)
  5.                 return false;
  6.                else if (col == 0)
  7.                    return true;
  8.             else {
  9.                 return (getValueAt(row, 0).equals(new Boolean(true)));
  10.             }
  11.         }
  12.  
Thank you again,

-blazed
Jul 20 '07 #7
r035198x
13,262 8TB
Java passes everything by value. Don't be confused with passing refences. The refences are passed by value as well. The moment you forget that you become a good candidate for defenestration.
Jul 21 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Alan Hoffman | last post by:
Hi, Is it possible to create a JTable where the column is not all one type of Component. For example using a JTable to enter in values for an address where the first column is just JLabels and...
1
by: Ben Munday | last post by:
Hi all, I have a problem with a Checkbox in a JTable. When i add the Checkbox into the JTable it displays the String representation of the Checkbox, which is not what i want. So, i created a...
1
by: asd | last post by:
I need to make the cells in the 1st column look like the column header. I tried the following code but it didn't change anything: private void rendererTest() { TableColumn column =...
1
by: raysaun | last post by:
I am trying to set a TableCellEditor for a JTable, however, the editor never seems to get called. I can not even get a simplified version (below) to work. When I put a breakpoint on the return...
0
by: sivaprasad06 | last post by:
Hi, I have a editable combo box editor as a cell editor for JTable. I want use only key board to enter data into jtable. so i am using ALT+Down comobination for making cell editiable in the...
1
by: Salha | last post by:
Hello There, I have two question about the JTable in Java: 1. How can i fix the column width? I want to have one column widder than the other and not editable at runtime. 2. How can i have...
7
oll3i
by: oll3i | last post by:
i want to change the values in two columns one colum is a combobox and the secons column is editable too i want to get the value of that second column and the value of combobox and sent that...
1
by: thesti | last post by:
hi, can we change the color of the border of a cell / every cell in JTable? thx
5
by: moizpalitanawala | last post by:
Hello friends, How to add data to JTable from a .txt file. I had seen this code from one of the tutorial from java.com. This code doesnt take any input. But shows what is written in the array....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.