CHECK BOX not coming in TABLE : VERY URGENT

Hi all,

Please help me.. I created a table with four clooumns. everything is working fine , but problem is in lat column I want to show CheckBox.. But it is printing "java.lang.object@4121f" like values.

I also implemented method

public Class getColumnClass(int c)

{

return getValueAt(0, c).getClass();

}

i my TableModel. I am attaching whole code here.. please run it and see what is the problem ..

plaesae its URGENT as I already wasted so much time on this and now project deadline is too near..

here is code :

import javax.swing.JTable;

import javax.swing.table.AbstractTableModel;

import javax.swing.table.TableColumn;

import javax.swing.DefaultCellEditor;

import javax.swing.table.TableCellRenderer;

import javax.swing.table.DefaultTableCellRenderer;

import javax.swing.JScrollPane;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.SwingUtilities;

import javax.swing.JOptionPane;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JButton;

import javax.swing.JTextField;

import javax.swing.JCheckBox;

import java.awt.*;

import java.awt.event.*;

import java.util.Vector;

public class AddCharges extends JFrame implements ActionListener

{

private boolean DEBUG= true;

JButton bt_Add= new JButton("Add");

MyTableModel myModel= new MyTableModel();

JTable table= new JTable(myModel);

public AddCharges()

{

super("AddCharges");

table.setPreferredScrollableViewportSize(new Dimension(500, 70));

//create a panel for Controls

JPanel panelSouth= new JPanel(false);

JPanel panelNorth= new JPanel(false);

JPanel panelWest= new JPanel(false);

JButton bt_OK= new JButton("OK");

JButton bt_Cancel= new JButton("Cancel");

JButton bt_Delete= new JButton("Delete");

JButton bt_DeleteAll= new JButton("Delete All");

JLabel lb_Job= new JLabel("Job");

JTextField tf_Job= new JTextField();

JLabel lb_TotChargeAmt= new JLabel("Total Charge Amount");

JCustomTextField tf_TotChargeAmt= new JCustomTextField("xxxxxx.xx", '.', '?');

JLabel lb_RateStruct= new JLabel("Rate Structure");

JTextField tf_RateStruct= new JTextField();

lb_Job.setBounds(6, 3,100,20);

tf_Job.setBounds(100,3,80,20);

lb_TotChargeAmt.setBounds(220, 3,100,20);

lb_TotChargeAmt.setBounds(220, 3,80,20);

lb_RateStruct.setBounds(6, 30,100,20);

tf_RateStruct.setBounds(100,30,80,20);

//bt_OK.setBounds(100,3,80,20);

//bt_Cancel.setBounds(220, 3,100,20);

panelNorth.setLayout(null);

panelNorth.setBounds(500,500,500,100);

panelWest.setLayout(new GridLayout(3, 1));

panelSouth.setLayout(new GridLayout(1, 2));

panelNorth.add(lb_Job);

panelNorth.add(tf_Job);

panelNorth.add(lb_TotChargeAmt);

panelNorth.add(tf_TotChargeAmt);

panelNorth.add(lb_RateStruct);

panelNorth.add(tf_RateStruct);

panelSouth.add(bt_OK);

panelSouth.add(bt_Cancel);

panelWest.add(bt_Add);

panelWest.add(bt_Delete);

panelWest.add(bt_DeleteAll);

bt_Add.addActionListener( this );

//Create the scroll pane and add the table to it.

JScrollPane scrollPane = new JScrollPane(table);

//Set up column sizes.

try

{

initColumnSizes(table, myModel);

}

catch(Exception e1)

{

System.out.println("Error 1");

System.out.println("Error : " + e1);

}

//Fiddle with the Sport column's cell editors/renderers.

try

{

setUpChargeDesc(table.getColumnModel().getColumn(0));

}

catch(Exception e2)

{

System.out.println("Error 2");

System.out.println("Error : " + e2);

}

//Add the scroll pane to this window.

getContentPane().add(scrollPane, BorderLayout.CENTER);

getContentPane().add(panelNorth, BorderLayout.NORTH);

getContentPane().add(panelSouth, BorderLayout.SOUTH);

getContentPane().add(panelWest, BorderLayout.WEST);

addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

});

}

public void actionPerformed( ActionEvent e )

{

try

{

Object eventTarget = e.getSource();

if( eventTarget == bt_Add )

{

//System.out.println("Size : " + myModel.data.size());

myModel.data.addElement( new MyObj("add urs", new Integer(0), new Integer(0), new Boolean(false)) );

table.tableChanged( new javax.swing.event.TableModelEvent(myModel) ) ;

}

}

catch(Exception e3)

{

System.out.println("Error 3");

System.out.println("Error : " + e3);

}

}

/*

* This method picks good column sizes.

* If all column heads are wider than the column's cells'

* contents, then you can just use column.sizeWidthToFit().

*/

private void initColumnSizes(JTable table, MyTableModel model)

{

TableColumn column = null;

Component comp = null;

int headerWidth = 0;

int cellWidth = 0;

Object[] longValues = model.longValues;

try

{

for (int i = 0; i < model.getRowCount()-1; i++)

{

column = table.getColumnModel().getColumn(i);

try

{

comp = column.getHeaderRenderer().getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);

//column.getDefaultRenderer().getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);

headerWidth = comp.getPreferredSize().width;

}

catch (NullPointerException e)

{

System.err.println("Null pointer exception!");

System.err.println(" getHeaderRenderer returns null in 1.3.");

System.err.println(" The replacement is getDefaultRenderer.");

}

//System.out.println("Clas NAme : " + longValues.getClass());

comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent( table, longValues, false, false, 0, i);

cellWidth = comp.getPreferredSize().width;

if (DEBUG)

{

System.out.println("Initializing width of column "

+ i + ". "

+ "headerWidth = " + headerWidth

+ "; cellWidth = " + cellWidth);

}

//XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.

column.setPreferredWidth(Math.max(headerWidth, cellWidth));

}

}

catch(Exception e4)

{

System.out.println("Error 4");

System.out.println("Error : " + e4);

}

}

public void setUpChargeDesc(TableColumn chargeDesc)

{

//Set up the editor for the sport cells.

JComboBox comboBox = new JComboBox();

comboBox.addItem("New Additional Charge");

comboBox.addItem("Add. Charge Test");

comboBox.addItem("Billto ID");

comboBox.addItem("Speed reading");

comboBox.addItem("old Additional Charge");

comboBox.addItem("None");

comboBox.setEditable(true);

chargeDesc.setCellEditor(new DefaultCellEditor(comboBox));

//Set up tool tips for the ChargeDesc cells.

DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();

renderer.setToolTipText("Click for combo box");

chargeDesc.setCellRenderer(renderer);

//Set up tool tip for the ChargeDesc column header.

TableCellRenderer headerRenderer = chargeDesc.getHeaderRenderer();

if (headerRenderer instanceof DefaultTableCellRenderer)

{

((DefaultTableCellRenderer)headerRenderer).setToolTipText("Click to see a list of choices");

}

}

class MyTableModel extends AbstractTableModel

{

String[] columnNames = {"Charge Description",

"Charge",

"Reimburse",

"Fee Adv",

};

Vector data = new Vector(0,1);

public MyTableModel()

{

//MyObj temObj = new MyObj( "first", new Integer(1), new Integer(1), new Boolean(false) );

//data.addElement( temObj );

data.addElement( new MyObj( "New Additional Charge", new Integer(5), new Integer(5), new Boolean(false) ) );

data.addElement( new MyObj( "New Additional Charge", new Integer(51), new Integer(10), new Boolean(false) ) );

data.addElement( new MyObj( "New Additional Charge", new Integer(52), new Integer(15), new Boolean(false) ) );

data.addElement( new MyObj( "New Additional Charge", new Integer(53), new Integer(20), new Boolean(false) ) );

}

public Object[] longValues =

{

"New Additional Charge", new Integer(5), new Integer(5), Boolean.TRUE

};

public int getColumnCount()

{

return columnNames.length;

}

public int getRowCount()

{

int size = 0;

try

{

size = data.capacity();

}

catch(Exception e1)

{

System.out.println("Error in getting Row Size");

System.out.println("Error : " + e1);

}

return size;

}

public String getColumnName(int col)

{

return columnNames[col];

}

public Object getValueAt(int row, int col)

{

MyObj obj = (MyObj) data.elementAt( row );

Object tempObject = new Object();

try

{

if( obj != null )

{

if( col == 0 )

tempObject = (Object) obj.first;

else

if( col == 1 )

tempObject = (Object) obj.second;

else

if( col == 2 )

tempObject = (Object) obj.third;

else

if( col == 1 )

tempObject = (Object) obj.last;

}

}

catch(Exception e5)

{

System.out.println("Error 5");

System.out.println("Error : " + e5);

}

return tempObject;

}

/*

* JTable uses this method to determine the default renderer/

* editor for each cell. If we didn't implement this method,

* then the last column would contain text ("true"/"false"),

* rather than a check box.

*/

public Class getColumnClass(int c)

{

return getValueAt(0, c).getClass();

}

/*

* Don't need to implement this method unless your table's

* editable.

*/

public boolean isCellEditable(int row, int col)

{

//Note that the data/cell address is constant,

//no matter where the cell appears onscreen.

if (col >= 0 )

{

return true;

}

else

{

return false;

}

}

/*

* Don't need to implement this method unless your table's

* data can change.

*/

public void setValueAt(Object value, int row, int col)

{

if (DEBUG)

{

System.out.println(" Row = " + row);

System.out.println(" Col = " + col);

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

System.out.println(" Column value = " + getValueAt(row,col));

if (value == null && getValueAt(row,col) instanceof Integer)

value = new Integer(0);

if (value == null && getValueAt(row,col) instanceof String )

value = new String("None");

if (value != null && value.toString().trim().equals("") && getValueAt(row,col) instanceof String )

value = new String("None");

System.out.println("Setting value at " + row + "," + col

+ " to " + value

+ " (an instance of "

+ value.getClass() + ")");

System.out.println("Value at " + row + "," + col + " : " +

getValueAt(row,col) + " (an instance of "

+ getValueAt(row,col).getClass() + ")");

}

if (getValueAt(row,col) instanceof Integer && (value instanceof Integer))

{

//With JFC/Swing 1.1 and JDK 1.2, we need to create

//an Integer from the value; otherwise, the column

//switches to contain Strings. Starting with v 1.3,

//the table automatically converts value to an Integer,

//so you only need the code in the 'else' part of this

//'if' block.

System.out.println("in first if");

try

{

MyObj obj = (MyObj) data.elementAt( row );

if( col == 1 )

{

System.out.println("in if");

obj.second = new Integer(value.toString());

}

else

{

System.out.println("in else");

if( col == 2 )

{

System.out.println("in else - if");

obj.third = new Integer(value.toString());

}

}

fireTableCellUpdated(row, col);

}

catch (NumberFormatException e)

{

JOptionPane.showMessageDialog(AddCharges.this, "The \"" + getColumnName(col) + "\" column accepts only integer values.");

}

}

else

{

System.out.println("in first else");

MyObj obj = (MyObj) data.elementAt( row );

if( col == 0 )

obj.first = (String) value;

else

if( col == 3 )

obj.last = (Boolean) value;

fireTableCellUpdated(row, col);

}

if (DEBUG)

{

System.out.println("New value of data:");

printDebugData();

}

}

private void printDebugData()

{

int numRows = getRowCount();

int numCols = getColumnCount();

for (int i=0; i < numRows; i++)

{

System.out.print("row " + i + ":");

for (int j=0; j < numCols; j++)

{

System.out.print(" " + getValueAt(i,j));

}

System.out.println();

}

System.out.println("--");

}

}

class MyObj

{

String first;

Integer second;

Integer third;

Boolean last;

public MyObj( String f, Integer s, Integer t, Boolean l )

{

this.first= f;

this.second = s;

this.third= t;

this.last= l;

}

}

public static void main(String[] args)

{

AddCharges frame = new AddCharges();

frame.pack();

frame.setVisible(true);

}

}

[14068 byte] By [dhir_sanatkumar] at [2007-9-26 1:16:03]
# 1

i havent run your code but it seems to me the problem is that you create a myObj in your TableModel. why dont you create 4 Vectors or ArrayLists to contain your String, Integers, and Boolean.

ArrayList[] columns = new ArrayList[4]; //1 for each column

getValue(row,column) would then be something like this :

return columns[column].get(row);

much simpeler than your code i think.

Hope this helps

Mr Mean

Mr Mean at 2007-6-29 0:43:18 > top of Java-index,Archived Forums,Swing...
# 2
Thanks, But seems U not geeting the exact problem... what u told is correct , But in my case everything is working fine and correctly....BUT CHECKBOXES are not coming instead it is showing some STRING VALUEPlesaey to run my code first.. U'll get the exact PROBLEM
dhir_sanatkumar at 2007-6-29 0:43:18 > top of Java-index,Archived Forums,Swing...
# 3

Hi

Probably the problem is that DefaultCellRenderer is a subclass of JLabel, that is, in its setValue it uses the method toString() to fill in the cells.

You might try to implement your Renderer so its getTableCellRendererComponent() returns a JCheckBox when the cell belongs to that column instead of 'this'.

algernon28 at 2007-6-29 0:43:19 > top of Java-index,Archived Forums,Swing...
# 4

Hi, i cudn't go thro ur source code.

But try this. U will get CheckBox in table.

//method creating JTable with 2 columns. Uses a MyModel

//as model for the table

private void createTable() {

Vector col = new Vector();

col.addElement("Name");

col.addElement("Check value");

Vector data = new Vector(1,1);

Vector row1 = new Vector(1,1);

row1.add("Alias1");

row1.add(new Boolean(true));

Vector row2 = new Vector(1,1);

row2.add("Alias2");

row2.add(new Boolean(false));

Vector row3 = new Vector(1,1);

row3.add("Alias3");

row3.add(new Boolean(true));

Vector row4 = new Vector(1,1);

row4.add("Alias4");

row4.add(new Boolean(false));

Vector row5 = new Vector(1,1);

row5.add("Alias5");

row5.add(new Boolean(true));

data.add(row1);

data.add(row2);

data.add(row3);

data.add(row4);

data.add(row5);

MyModel model = new MyModel(data,col);

mTable = new JTable(model);

}//close createTable

***********************************************************

// Model class

import java.util.Vector;

import javax.swing.table.DefaultTableModel;

//

/**

* MyModel is a Model which is set to the table

* in InventoryMainNavigation

* <p>

*

* <b>Purpose:</b>

* Its extends DefaultTableModel

* To set the cells in table to noneditable mode

* <p>

*

* <b>Requires:</b>

*

* <p>

*

*/

//

public class MyModel extends DefaultTableModel {

//--

/**

* Creates MyModel with no rows and rows

* <p>

*

*

*/

public MyModel() {

}

//--

/**

* Creates the MyModel

* <p>

*

* @param aData : Vector containing data for rows

* @param aColNames : Vector containing coloumn names

*/

public MyModel(Vector aData,Vector aColNames) {

super(aData,aColNames);

}

//--

/**

* Creates the MyModel

* <p>

*

* @param aData : Object 2 dimensional array containing data for rows

* @param aColNames : Object 2 dimensional array containing coloumn names

*/

public MyModel(Object[][] aData,Object[] aColNames) {

super(aData,aColNames);

}

//--

/**

* Creates the MyModel

* <p>

*

* @param aRows : an int indicating number of rows

* @param aCols : an int indicating number of columns

*/

public MyModel(int aRows,int aCols) {

super(aRows,aCols);

}

//--

/**

* Creates the MyModel

* <p>

*

* @param aColNames : Vector containing names of columns

* @param aNoRows : an int indicating number of rows

*/

public MyModel(Vector aColNames,int aNoRows) {

super(aColNames,aNoRows);

}

//--

/**

* Sets cells to non editable mode

* <p>

* <b>Promises:</b>

* To return a boolean false

*

* @param aRow : an int indicating row number

* @param aCol : an int indicating column number

* <p>

*/

public boolean isCellEditable(int aRow,int aCol) {

return false;

}

public Class getColumnClass(int c) {

return getValueAt(0, c).getClass();

}

}

Hope it will be useful

raghavendrajoshi at 2007-6-29 0:43:19 > top of Java-index,Archived Forums,Swing...