473,884 Members | 2,358 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Changing the editability of a JTable cell through a TableModelEvent

blazedaces
284 Contributor
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 AbstractTableMo del 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 17238
JosAH
11,448 Recognized Expert MVP
My issue is this: is there a way to access the methods of an AbstractTableMo del 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 Contributor
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 Contributor
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 Recognized Expert MVP
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 Contributor
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 Contributor
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 MVP
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
1934
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 the second columns first cell is a JTextField for the street and the next cell is a JComboBox that contains all the states. Thanks, Alan
1
8640
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 CheckBoxRenderer which extens Checkbox and implements TableCellRenderer. This seems to have done the job, in that the Checkbox is displayed and not the String representation. But, and it's a big 'but', the column that holds the Checkbox continually...
1
8978
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 = tblDecisions.getColumnModel().getColumn(0); TableCellRenderer renderer = column.getHeaderRenderer(); column.setCellRenderer(renderer); }
1
7986
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 statement in getTableCellEditorComponent, it never stops there even though I edit cells in the table. Can anyone tell me what I am missing. By the way, I have gotten TableCellRenderers to work with no problems. public class Frame1 extends...
0
3149
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 jtable. when user clicks that combination what ever editor present in that cell will appear. I am using tab for traversing all cells in table.
1
1733
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 multiple lines (block of data/small paragraph) in one cell? because whenver i write a 3 lines of data in a cell the JTable converts it cont. line. Please Help!!
7
3762
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 to another application i have setValueAt(Object value,int row, int col) but it works only for combobox when i enter some data in the second editable column the value i entered disappears rows are a list data = new...
1
12888
by: thesti | last post by:
hi, can we change the color of the border of a cell / every cell in JTable? thx
5
9876
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. But i want the table to display the data from a .txt file in which i had stored information in this format. Can anyone please modify the codes and explain me. Name:Mr.xyz Phone:111111222222
0
9954
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9799
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10769
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10869
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10426
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9591
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7137
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
4231
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3242
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.