This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JTable selected row problem  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTable selected row problem  " Watch "JTable selected row problem  " New topic
Author

JTable selected row problem

seema prakash
Ranch Hand

Joined: Nov 17, 2004
Posts: 59
Hi,

I have a jtable with different editors for the columns.
The first column(col 0) had a combobox editor and renderer.
The second col(col 1) has a combobox editor and the default editor(jtextfield) depending upon the selection in the jcombobox of the first column.

First I add a row and in the first combo box I choose "Non Work" item. Then I add another row and choose "Exclude" item from the first combo box. The display is fine. But, now When I go to the first row(row 0)
and first col(col 0) to choose a different item, the selected row has to be 0 but instead it shows 1. I have a print statement that prints the selected row value on the console. That is the reason col 1 displays wrong value. I'm not sure why this happens. Please help.

My sample code for the table and the main is below:

{code}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class BusinessRuleTable extends JTable {

String[] colNames = new String[] { "RuleType", "Date", "Action/Type", "Description" };

private DefaultTableModel _model = null;
private CWComboBoxEditor editor1 = null;
private CWComboBoxEditor editor2 = null;
private CWComboBoxEditor editor3 = null;
private CWComboBoxEditor editor4 = null;
private BusinessRuleDateColEditor dateEditor = null;
private CWComboBoxRenderer renderer = null;
private JComboBox comboBox1 = null;
private JComboBox comboBox2 = null;
private JComboBox comboBox3 = null;
private JComboBox comboBox4 = null;

public BusinessRuleTable(DefaultTableModel model){
_model = model;

_model.setColumnIdentifiers(colNames);
this.setModel(_model);

//Use a combo box as the editor
editor1 = new CWComboBoxEditor(getComboBox1(loadRuleTypeValues()));
JComboBox cbx1 = (JComboBox) editor1.getComponent();
cbx1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

if(e.getSource() instanceof JComboBox){
JComboBox o = (JComboBox) e.getSource();
String str = (String) o.getSelectedItem();
int selectedRow = BusinessRuleTable.this.getSelectedRow();

System.out.println("selectedRow = "+selectedRow);

if(BusinessRuleTable.this.getSelectedRow() >-1){
if(str.equals("Exclude")){
BusinessRuleTable.this.setValueAt("Gregorian", BusinessRuleTable.this.getSelectedRow(), 2);
BusinessRuleTable.this.setValueAt("", BusinessRuleTable.this.getSelectedRow(), 1);
}
else if(str.equals("Non Work")){
BusinessRuleTable.this.setValueAt("RollForward", BusinessRuleTable.this.getSelectedRow(), 2);
BusinessRuleTable.this.setValueAt("Sunday", BusinessRuleTable.this.getSelectedRow(), 1);
}else if(str.equals("Holiday")){
BusinessRuleTable.this.setValueAt("RollForward", BusinessRuleTable.this.getSelectedRow(), 2);
BusinessRuleTable.this.setValueAt("", BusinessRuleTable.this.getSelectedRow(), 1);
}
}
}

}});
editor2 = new CWComboBoxEditor(getComboBox2(loadActionTypeForExclude()));
editor3 = new CWComboBoxEditor(getComboBox3(loadActionTypeForHolidayAndNonWork()));
editor4 = new CWComboBoxEditor(getComboBox4(loadDateForHoliday()));

renderer = new CWComboBoxRenderer();

}

private JComboBox getComboBox1(List items){
if(comboBox1 == null){
comboBox1 = new JComboBox();
}
comboBox1.removeAllItems();
comboBox1.setEditable(false);

Iterator iter = items.iterator();
while (iter.hasNext()) {
comboBox1.addItem(iter.next());
}
return comboBox1;
}

private JComboBox getComboBox2(List items){
if(comboBox2 == null){
comboBox2 = new JComboBox();
}
comboBox2.removeAllItems();
comboBox2.setEditable(false);
Iterator iter = items.iterator();
while (iter.hasNext()) {
comboBox2.addItem(iter.next());
}
return comboBox2;
}

private JComboBox getComboBox3(List items){
if(comboBox3 == null){
comboBox3 = new JComboBox();
}
comboBox3.removeAllItems();
comboBox3.setEditable(false);

Iterator iter = items.iterator();
while (iter.hasNext()) {
comboBox3.addItem(iter.next());
}
return comboBox3;
}

private JComboBox getComboBox4(List items){
if(comboBox4 == null){
comboBox4 = new JComboBox();
}
comboBox4.removeAllItems();
comboBox4.setEditable(false);

Iterator iter = items.iterator();
while (iter.hasNext()) {
comboBox4.addItem(iter.next());
}
return comboBox4;
}

List loadRuleTypeValues(){
List ruleTypeValues = new ArrayList();
ruleTypeValues.add("Exclude");
ruleTypeValues.add("Non Work");
ruleTypeValues.add("Holiday");
return ruleTypeValues;
}

List loadActionTypeForExclude(){
List lst = new ArrayList();
lst.add("Gregorian");
lst.add("Julian");
return lst;
}

List loadActionTypeForHolidayAndNonWork(){
List lst = new ArrayList();
lst.add("RollForward");
lst.add("RollBackward");
return lst;
}

List loadDateForHoliday(){
List lst = new ArrayList();
lst.add("Monday");
lst.add("Tuesday");
lst.add("Wednesday");
lst.add("Thursday");
lst.add("Friday");
lst.add("Saturday");
lst.add("Sunday");
return lst;
}

public TableCellEditor getCellEditor(int row, int col) {
if(col == 0 ){
return editor1;
} else if (col == 2) {
Object value = getModel().getValueAt(row, 0);

if(value.equals("Exclude")){
//set editor2 for col2
return editor2;
}else if(value.equals("Holiday") || value.equals("Non Work")){
//set editor3 for col2
return editor3;
}else {
return editor2;
}
} else if (col == 1) {
Object value = getModel().getValueAt(row, 0);
if(value.equals("Non Work")){
return editor4;
}

}

return super.getCellEditor(row, col);
}

public TableCellRenderer getCellRenderer(int row, int column) {

if (column == 0 || column == 2) {
return renderer;
}

if (column == 1){
Object value = getModel().getValueAt(row, 0);
if(value.equals("Non Work")){
return renderer;
}
}
return super.getCellRenderer(row, column);
}

}



{code}

{code}

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;

public class BusinessRuleTest1 extends JFrame {

private BusinessRuleTable tblSelection;
private DefaultTableModel tblSelectionModel;
/**
* Constructor
*/
public BusinessRuleTest1(){
tblSelectionModel = new DefaultTableModel();

tblSelection = new BusinessRuleTable( tblSelectionModel );
tblSelection.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
int col = tblSelection.getSelectedColumn();
int row = tblSelection.getSelectedRow();
System.out.println("col = " + col + "row = "+row);
}
});

getContentPane().add( new JScrollPane( tblSelection ), BorderLayout.CENTER );

JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int rows = tblSelectionModel.getRowCount();
Object rowData[] = { "", "", "" };
tblSelectionModel.insertRow(rows , rowData);
}
});
getContentPane().add(btnAdd, BorderLayout.SOUTH);
}

static void createAndShowGUI() {
BusinessRuleTest1 frame = new BusinessRuleTest1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

}


{code}

The code for the editor and renderer are below:
{code}

import java.awt.Component;
import java.util.Vector;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
/**
* Returns a JComboBox as the editor in sync with the CWComboBoxRenderer
*
*/
public class CWComboBoxEditor extends DefaultCellEditor implements TableCellEditor{
/**
* Constructor for the CWComboBoxEditor object
*
*@param cbr Description of the Parameter
*/

public CWComboBoxEditor(JComboBox cbx) {
super(cbx);
}


/**
* Constructor for the CWComboBoxEditor object
*
*@param vector Description of the Parameter
*/
public CWComboBoxEditor(Vector vector) {
super(new JComboBox(vector));
}


/**
* Constructor for the CWComboBoxEditor object
*
*@param objects Description of the Parameter
*/
public CWComboBoxEditor(Object[] objects) {
super(new JComboBox(objects));
}


/**
* Gets the tableCellEditorComponent attribute of the CWComboBoxEditor
* object
*
*@param table Description of the Parameter
*@param value Description of the Parameter
*@param isSelected Description of the Parameter
*@param row Description of the Parameter
*@param col Description of the Parameter
*@return The tableCellEditorComponent value
*/
public Component getTableCellEditorComponent
(JTable table, Object value,
boolean isSelected,
int row, int col) {

return super.getTableCellEditorComponent(table, value, isSelected, row, col);
}


}

{code}
{code}

import java.awt.Component;

import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.DefaultTableCellRenderer;

public class CWComboBoxRenderer extends JComboBox implements TableCellRenderer {


Border border = new EmptyBorder(1,2,1,2);
DefaultTableCellRenderer defaultRenderer = new DefaultTableCellRenderer();

/**
* Constructor for the CWComboBoxRenderer object
*/
public CWComboBoxRenderer() {
super();
}

/**
* Gets the tableCellRendererComponent attribute of the CWComboBoxRenderer
* object
*
*@param table Description of the Parameter
*@param value Description of the Parameter
*@param isSelected Description of the Parameter
*@param hasFocus Description of the Parameter
*@param row Description of the Parameter
*@param column Description of the Parameter
*@return The tableCellRendererComponent value
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {

//
// Render non-editable cells using the default table cell renderer (i.e. JLabel)
//
if (!table.isCellEditable(row, column)) {
return defaultRenderer.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
}

//
// Render editable cells using a JComboBox
//
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
if (hasFocus)
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
else
setBorder(border);

this.removeAllItems();
this.addItem(value);

return this;

}

/**
* return Look and Feel button width.
*/
public static int getComboButtonWidth() {
return 20;

}

}

{code}

Thanks.
seema prakash
Ranch Hand

Joined: Nov 17, 2004
Posts: 59
Sorry the code is not formatted correctly.

Here is the formatted one.

My sample code for the table and the main is below:





The code for the editor and renderer are below:



Thanks.
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
When the user selects a new row the getCellEditor method is
called (with the row) for an editor. Use this to set the (new/added)
selectedRow member variable:
seema prakash
Ranch Hand

Joined: Nov 17, 2004
Posts: 59
Hi,
Thanks for the reply. But, I still have the same problem.
It still shows the wrong selected row value.
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
First I add a row and in the first combo box I choose "Non Work" item. Then I add another row and choose "Exclude" item from the first combo box. The display is fine. But, now When I go to the first row(row 0)
and first col(col 0) to choose a different item, the selected row has to be 0 but instead it shows 1. I have a print statement that prints the selected row value on the console. That is the reason col 1 displays wrong value. I'm not sure why this happens

I copied, pasted, compiled and ran your code. It behaved as you desctibed. I tried to come up with my own way to implement what you are trying to do but didn't get very far. Then I tried setting the "selectedRow" from within the getCellEditor method and it worked, and still works, okay: the selected row is correctly reported with each mouseClick in column 0 on a different row. Something must be different in the code we are running.
seema prakash
Ranch Hand

Joined: Nov 17, 2004
Posts: 59
Thanks a lot for the help. Yes, I had used the member variable as you said. But, instead of eliminating it, I assigned the variable the value table.getSelectedRow() instead of just using the variable. I corrected it. It works fine as desired.
 
Don't get me started about those stupid light bulbs.
 
subject: JTable selected row problem
 
Similar Threads
How do I display two columns in my jcombobox?
Combo Selection - Trouble
JComboBox and "long" items rendered via HTML
Netbeans GUI Code Doubt
ActionListener problem