?
Solved

How to know when the Jtable get updated.

Posted on 2003-03-18
16
Medium Priority
?
247 Views
Last Modified: 2012-08-13
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
Comment
Question by:waterdrop
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
16 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 8160247
 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
 

Author Comment

by:waterdrop
ID: 8171291
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
 
LVL 35

Expert Comment

by:girionis
ID: 8172910
 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:waterdrop
ID: 8174028
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
 
LVL 35

Expert Comment

by:girionis
ID: 8175013
 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
 

Author Comment

by:waterdrop
ID: 8177880
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
 
LVL 35

Expert Comment

by:girionis
ID: 8179685
 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
 

Author Comment

by:waterdrop
ID: 8212710
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
 

Author Comment

by:waterdrop
ID: 8212801
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
 
LVL 35

Expert Comment

by:girionis
ID: 8212846
 Can you post a small compilable example of your JTable and I will try to have a look.
0
 

Author Comment

by:waterdrop
ID: 8212950
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
 

Author Comment

by:waterdrop
ID: 8212961
thanks...
0
 
LVL 35

Expert Comment

by:girionis
ID: 8219013
 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
 

Author Comment

by:waterdrop
ID: 8219595
yes..
0
 

Author Comment

by:waterdrop
ID: 8219601
because I just cut the middle of the code, it will not compile...
0
 
LVL 35

Accepted Solution

by:
girionis earned 750 total points
ID: 8261939
 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month9 days, 11 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question