• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 256
  • Last Modified:

How to know when the Jtable get updated.

I have Jtable and DefaultTableModel.  4 columns in the table.  2 of 4 column is editable.  One is combobox, the other is textfield.   how do I know the user update these two columns and how to get the new values of these two columns?  Other thing is when the user update the two column, I don't want the whole row is selected.  any idea or code appreciate.
0
waterdrop
Asked:
waterdrop
  • 9
  • 7
1 Solution
 
girionisCommented:
 You need to listen to the model of the table. Table models fire events in the TableModelListener interface. You need to implement this interface and add a listener to the tabel model. take a look here:

http://javaalmanac.com/egs/javax.swing.table/ValueEvent.html
http://javaalmanac.com/egs/javax.swing.table/pkg.html
0
 
waterdropAuthor Commented:
if I use table.setCellSelectionEnabled(false); I can't select row at all.  
This still can't solve my problem.

for example, the 4 column is c1,c2,c3,c4, c2 is using combobox, c3 is using textfield, this 2 column and c3 are setcellselectionEnabled(false).  if user press c1 or c4, the whole row is selected. Can I do that?  Thanks.
0
 
girionisCommented:
 If you set a cell selection to false then you cannot do any changes to that cell anyway. When you use the setCellSelectionEnabled method and you set it to false this will disallow *both* a column selection and a row selection to exist simultaneously, since selecting a cell can be done in two ways, either selecting the column or either selectign the row.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
waterdropAuthor Commented:
I use row selected:

table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.setCellSelectionEnabled(false);

when the user press c1, c4, the whole row didn't high light.  What should I use?  Thanks
0
 
girionisCommented:
 Does the row include a cell that is set not to be editable? If yes then you cannot do it since the cell will now allow to be selected. If the cell that cannot be selected is in the row you try to select then this cannot be done.
0
 
waterdropAuthor Commented:
if I didn't use table.setCellSelectionEnabled(false);
it works fine.  below is my code.

mymodel = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
     if(mColIndex == 1)
          return true;
        return false;
    }
};

table = new JTable(mymodel);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
0
 
girionisCommented:
 First of all is your first part of the question solved?

  Second, if you use setColumnSelectionAllowed(false) you can select a row since the setColumnSelectionAllowed(false) will only disable the column selection and not the row selection. If you use setCellSelectionEnabled(false) then you disable both column and row of being selected since the cell is in the intersection of the column and row.

  Can you explain a bit more what you are trying to do? Can you also post a small compilable example?
0
 
waterdropAuthor Commented:
thanks..  sorry, I didn't check this side for a long time.

what I try to do is

_____________________________________________________
fist name|   last name    |   sports    |   score
_____________________________________________________
Jack     |   Thompson     |  Basketball |     11
_____________________________________________________
Helen    |   Inv         |   Football   |     22
_____________________________________________________

if user press on the column first name or last name, the whole row will select, if user press on the column sports,
it will have combobox to show up and ask user to select one.  if user press on the column score, user can edit the column score.

for this example, if user press on "Jack" or "Thompson", the first row will selected and highlight.  if user press on "Basketball", the combobox will show up, but not first row selected or highlight.
0
 
waterdropAuthor Commented:
for the first part question, I don't have time to understand the table listener part.
I just use the easy way to do the first part, use the combobox and textfield actionlistener to do the first part.  

0
 
girionisCommented:
 Can you post a small compilable example of your JTable and I will try to have a look.
0
 
waterdropAuthor Commented:
because my code is in the big application.  I just cut part of it...

************************table******************
             mymodel = new DefaultTableModel() {
              public boolean isCellEditable(int rowIndex, int mColIndex) {
                        if(mColIndex == 1)
                              return true;
                  return false;
              }
            };

             // Add a column using the simple method
          mymodel.addColumn("Property Name");
          mymodel.addColumn("Restrictive on");
          mymodel.addColumn("Value");
          mymodel.addColumn("toClass");
          mymodel.addColumn("hasClass");
          mymodel.addColumn("hasValue");


        my_table = new JTable(mymodel);
                 my_table.setColumnSelectionAllowed(false);
                my_table.setRowSelectionAllowed(true);
          my_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

            if(currentclass.getPropnum() > 0)
            {
                  Vector propClass = currentclass.getProTypes();
                  Enumeration propnum = propClass.elements();
                  restrictionDetail res;
                  while(propnum.hasMoreElements())
                  {
                        res = (restrictionDetail)propnum.nextElement();
                        mymodel.addRow(new Object[]{res.getProp(), res.getRestriction(),res.getValues(),res.gettoClass(),res.gethasClass(),res.gethasValue()});
                  }
            }
        //Fiddle with the Sport column's cell editors/renderers.
        setUpSportColumn(my_table.getColumnModel().getColumn(1));

        my_table.setPreferredScrollableViewportSize( new Dimension(345,120) );
        //my_table.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN );
        my_table.setAutoCreateColumnsFromModel( false );
            my_table.setCellSelectionEnabled(false);
        //my_table.sizeColumnsToFit(-1);
        JScrollPane tablescp = new JScrollPane(my_table);
        tablescp.getViewport().setBackground(Color.white);


-----------------------------------------
    public void setUpSportColumn(TableColumn sportColumn) {
        //Set up the editor for the sport cells.
        comboBox = new JComboBox();
        comboBox.addItem("None");
        comboBox.addItem("Cardinality");
        comboBox.addItem("minCardinality");
        comboBox.addItem("maxCardinality");
        comboBox.addItem("CardinalityQ");
        comboBox.addItem("minCardinalityQ");
        comboBox.addItem("maxCardinalityQ");

        comboBox.addItemListener(new ItemListener() {
                    // This method is called only if a new item has been selected.
                public void itemStateChanged(ItemEvent evt) {
                    JComboBox cb = (JComboBox)evt.getSource();
                    int row;

                    if (evt.getStateChange() == ItemEvent.SELECTED) {
                             restriction.setRestriction(evt.getItem().toString());
                             String resString = evt.getItem().toString();
                              if(resString.equals("Cardinality"))
                              {
                                    restriction.setValues(""+propD.getCard());
                                 row = my_table.getSelectedRow();
                                 my_table.getModel().setValueAt(""+propD.getCard(), row, 2);
                              } else if(resString.equals("minCardinality"))
                              {
                                    restriction.setValues(""+propD.getminCardinality());
                                 row = my_table.getSelectedRow();
                                 my_table.getModel().setValueAt(""+propD.getminCardinality(), row, 2);
                              } else if(resString.equals("maxCardinality"))
                              {
                                    restriction.setValues(""+propD.getmaxCardinality());
                                 row = my_table.getSelectedRow();
                                 my_table.getModel().setValueAt(""+propD.getmaxCardinality(), row, 2);
                              } else if(resString.equals("CardinalityQ"))
                              {
                                    restriction.setValues(""+propD.getCardQ());
                                 row = my_table.getSelectedRow();
                                 my_table.getModel().setValueAt(""+propD.getCardQ(), row, 2);
                              } else if(resString.equals("minCardinalityQ"))
                              {
                                    restriction.setValues(""+propD.getminCardinalityQ());
                                 row = my_table.getSelectedRow();
                                 my_table.getModel().setValueAt(""+propD.getminCardinalityQ(), row, 2);
                              } else if(resString.equals("maxCardinalityQ"))
                              {
                                    restriction.setValues(""+propD.getmaxCardinalityQ());
                                 row = my_table.getSelectedRow();
                                 my_table.getModel().setValueAt(""+propD.getmaxCardinalityQ(), row, 2);
                              } else {
                                    restriction.setValues("");
                              }
                    }
                }
            });

        sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

        //Set up tool tips for the sport cells.
        DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);

        //Set up tool tip for the sport column header.
        TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
        if (headerRenderer instanceof DefaultTableCellRenderer) {
            ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
                     "Click the restrictive to see a list of choices");
        }
    }
**************************************************
0
 
waterdropAuthor Commented:
thanks...
0
 
girionisCommented:
 Hmm.. you code has too many compile problems... It will be better just to write a sample table code and do what you want. Now to get things clear.

>for this example, if user press on "Jack" or "Thompson", the first row will selected and highlight.  if user press on "Basketball", the combobox will show up,
> but not first row selected or highlight.

  So when the user clicks on the combo box you do not want the whole row to be highlighted? YOu just want the user to select something from the combo box but you do not want the rest of the row to be highlighted? Is that what you want to do?
0
 
waterdropAuthor Commented:
yes..
0
 
waterdropAuthor Commented:
because I just cut the middle of the code, it will not compile...
0
 
girionisCommented:
 Since I had problems compiling your application I just wrote a sample one real quick to demonstrate how you can achieve that you are trying to. Basically all it does is to have a few values on the table and when you select a cell (regardless if it is a combo box or any other cell) it just highlights this cell and leaves the rest of the row unaffected.

  You can compile it and see how it works. If this is not what you are looking for let me know :-)

  import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class JTableTest extends JFrame
{
      private JTable table = null;
      private JComboBox comboBox = null;
      
      public static void main(String [] arguments)
      {
            JTableTest tt = new JTableTest();
            tt.pack();
            tt.setVisible(true);
      }
      
      public JTableTest()
      {
            String [] columnNames = {"First Name", "Last Name", "Sports", "Score"};
            String [][] tableData = { {"Jack", "Thompson", "Basketball", "11"},
                                                 {"Hellen", "Inv", "Footbal", "22"}
                                                };

            // Create table with data and columns
            table = new JTable(tableData, columnNames);
            table.setRowSelectionAllowed(false);
            // Add table to scroll pane.
            JScrollPane scrollPane = new JScrollPane(table);
            // Add scroll pane to this window
        getContentPane().add(scrollPane, BorderLayout.CENTER);
       
        TableColumn sportColumn = table.getColumnModel().getColumn(2);
            comboBox = new JComboBox();
            comboBox.addItem("Footbal");
            comboBox.addItem("Basketball");
            sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
            
            comboBox.addActionListener(new ActionListener()
                                                      {
                                                            // Trick to get only the second value of the combo box.
                                                            // When the user clicks on the combo box to select it
                                                            // then the combo box click is treated like a value. We
                                                            // only want the second value.
                                                            boolean second = false;
                                                            public void actionPerformed(ActionEvent e)
                                                            {
                                                                  if (second)
                                                                  {
                                                                        System.out.println("value: " + comboBox.getSelectedItem());
                                                                        second = false;
                                                                  }
                                                                  else
                                                                  {
                                                                        second = true;
                                                                  }
                                                            }
                                                      }
                                                );
            // Add a listener for window closing events
            addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        // Add a listener to the table for mouse events.
        table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    getValue();
                }
            });

      }
      
      // Displays the value of the table's cell
      public void getValue()
      {
            System.out.println("value: " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
      }
}
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 9
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now