Results 1 to 6 of 6
  1. #1
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default JTable setCellEditor(), setCellRenderer()

    Hi, here again :)
    I have problems that I have been solving for almost a week (yes.. almost a week). I've been trying to understand setCellRenderer and setCellEditor method of JTable, I copy the code from internet and trying to modify it base on my understanding and what I want to happen. I cant figure out what I've done wrong and dont know how to solve this, so I write a small program as part of trying to debug it and run that small program, but what happen is different in what is happening in Netbeans. Everything is the same with the original code except from connecting in database to populate the JTable.

    at first click in the button in Jtable the (I use System.out.println to see which method run.)
    [b]OUTPUT FROM SMALL PROGRAM IS:[b]
    Java Code:
        Button Editor       <--- Button Editor is ButtonEditor() method.
        EDITOR editable     <--- EDITOR editable is isCellEditable() method.

    [b]OUTPUT FROM NETBEANS IS:[b]
    Java Code:
        Button Editor       <--- Button Editor is ButtonEditor() method.
        EDITOR Editable     <--- EDITOR editable is isCellEditable() method.
        EDITOR COMPONENT    [b]<--- EDITOR COMPONENT is getTableCellEditorComponent() method. Small program does not have this output[b]
        //If i am not mistaken methods below run because EDITOR COMPONENT run
        Button Pressed
        Add Cell Editor
        Should Select Cell

    at Second click in the button in Jtable the
    [b]OUTPUT FROM SMALL PROGRAM IS:[b]
    Java Code:
        EDITOR editable     <--- EDITOR editable is isCellEditable() method.

    [b]OUTPUT FROM NETBEANS IS: NOTHING[b]


    Here is the code FROM SMALL PROGRAM:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableCellEditor;
    
    public class JTableButton1 extends JFrame
    {	private JTable tbl;
    	Object[][] objData;
        	String[] tableHeader;
    
        	public JTableButton1()
    	{
            		initComponents();
    
             		objData = new Object[][]{  {"Krung2x", "Gruwler", "Soghfier"},
                                        	  {"Jewlica", "Eqoe", "Mercedes"}};
             		tableHeader = new String[]{"FIRST NAME", "MIDDLE NAME", "LAST NAME"};
             		addTableData();
             		cellRender();
    	}
    
        	private void initComponents() 
    	{	tbl = new JTable();
    
            		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		this.setLayout(new BorderLayout());
    		this.add(tbl, BorderLayout.CENTER);
            		tbl.setPreferredSize(new Dimension(500, 100));
            		pack();
        	}
    
    	public static void main(String args[])
    	{	EventQueue.invokeLater(new Runnable()
    		{
                			public void run()
    			{new JTableButton1().setVisible(true);
                			}
            		});
        	}
    
        	void addTableData()
        	{	tbl.setModel(new DefaultTableModel(objData, tableHeader)
            		{	@Override
                			public boolean isCellEditable(int row, int column)
                			{	boolean editable = false;
    				if(column == 0){editable = true;}
    				return editable;
    			}
            		});
        	}
    
        	void cellRender()
        	{	TableColumn tc = new TableColumn();
            		tc = tbl.getColumn("FIRST NAME");
            		tc.setCellRenderer(new ButtonRenderer());
            		tc.setCellEditor(new ButtonEditor());
        	}
    
    
    /************************************ .:: START: Button Renderer ::. *******************************************/
    	class ButtonRenderer extends JButton implements TableCellRenderer
    	{
    		public ButtonRenderer()
    		{
        			setOpaque(true);
      		}
    
      		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    		{
        			if (isSelected)
    			{	setForeground(table.getSelectionForeground());
          				setBackground(table.getSelectionBackground());
        			}
    			else
    			{
          				setForeground(table.getForeground());
          				setBackground(UIManager.getColor("Button.background"));
        			}
        			setText( (value ==null) ? "" : value.toString() );
        			return this;
      		}
    	}
    /************************************ .:: END: Button Renderer ::. *******************************************/
    
    
    
    /************************************ .:: START: Button Editor ::. *******************************************/
    	class ButtonEditor extends JButton implements TableCellEditor
    	{	JTable table;
        		Object value;
        		boolean isSelected;
        		int row, column;
    
        		public ButtonEditor()
    		{	super("VIEW");
            			System.out.println("Button Editor");
        		}
    
        		public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected, int row, int column)
    		{	this.table = table;
            			this.value = value;
            			this.isSelected = isSelected;
            			this.row = row;
            			this.column = column;
            			if(value == null || (value instanceof String && value.toString().length() <= 0))
            			{	value = "VIEW";
            			}
            			buttonPressed(table, row, column);
            			System.out.println("EDITOR COMPONENT");
            			return this;
        		}
    
        		public void cancelCellEditing()
    		{	System.out.println("Cancel");
        		}
    
        		public boolean stopCellEditing()
    		{	System.out.println("CELL EDITING");
            			return true;
        		}
    
        		public Object getCellEditorValue()
    		{	System.out.println("EDITOR VALUE");
            			buttonPressed(table, row, column);
            			isSelected = true;
            			return value;
        		}
    
        		public boolean isCellEditable(EventObject anEvent)
    		{	System.out.println("EDITOR Editable");
            			return false;
        		}
    
        		public boolean shouldSelectCell(EventObject anEvent)
    		{	System.out.println("Should Select Cell");
            			return true;
        		}
    
        		public void addCellEditorListener(CellEditorListener l)
    		{	System.out.println("Add Cell Editor");
        		}
    
        		public void removeCellEditorListener(CellEditorListener l)
    		{	System.out.println("remove Cell Editor");
        		}
    
        		protected void fireCellEditing(ChangeEvent e)
    		{	System.out.println("fire cell editing");
    		}
    
        		private void buttonPressed(JTable table, int row, int column)
    		{	System.out.println("Button Pressed");
            			String fn, mn, ln;
            			Object tblVlaue;
    
            			tblVlaue = table.getValueAt(row, 0);
            			if(tblVlaue == null || (tblVlaue instanceof String && tblVlaue.toString().length() <= 0))
            			{   fn = "0";
            			}
            			else
            			{	fn = tblVlaue.toString();
    			}
    
           			tblVlaue = table.getValueAt(row, 1);
            			if(tblVlaue == null || (tblVlaue instanceof String && tblVlaue.toString().length() <= 0))
            			{   mn = "0";
            			}
            			else
            			{mn = tblVlaue.toString();}
    
            			tblVlaue = table.getValueAt(row, 2);
            			if(tblVlaue == null || (tblVlaue instanceof String && tblVlaue.toString().length() <= 0))
            			{   ln= "0";
            			}
            			else
            			{ln = tblVlaue.toString();}
    
    			System.out.println(fn + " " + mn + " " + ln);
            			//new FrmMatDelViewer(fn, mn, ln).setVisible(true);
            			//isSelected = true;
        		}
    	}
    /************************************ .:: END: Button Editor ::. *******************************************/
    }
    Thanks,
    geje

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    1) What is the small program not doing that you want it to be doing?
    2) What is it doing that it shouldn't be doing?
    3) Why do you have the result of the ButtonEditor#isCellEditable method return false?

  3. #3
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

    I also don't understand what you are attempting to do, but for what its worth here is my version of a button renderer/editor that might help with your understanding:

    Table Button Column Java Tips Weblog

  4. #4
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    1) What is the small program not doing that you want it to be doing?
    2) What is it doing that it shouldn't be doing?
    From the original work from netbeans I just copy-paste the ButtonRenderer() and ButtonEditor() to the 'small program' so I am expecting its result should be the same with netbean's result.

    3) Why do you have the result of the ButtonEditor#isCellEditable method return false?
    I was trying to experiment in the small program by changing return values and maybe I forgot to change it back to true. And I found out that this what makes it different in netbeans program.


    I also don't understand what you are attempting to do, but for what its worth here is my version of a button renderer/editor that might help with your understanding:
    I just want to make a Jbutton in JTable and properly execute an event when user clicks that button. But I failed. I have seen your reply in a forum, its a bit different with the link you gave me. I tried your code and it works great it is also easy to understand. In the example you gave in the said forum I've seen that you use the method getColumnClass(), but in the blog you did not use it, why?
    Java Code:
        public TableButton3()
        {
            String[] columnNames = {"Date", "String", "Integer", "Decimal", ""};
            Object[][] data =
            {
                {new Date(), "A", new Integer(1), new Double(5.1), "Delete0"},
                {new Date(), "B", new Integer(2), new Double(6.2), "Delete1"},
                {new Date(), "C", new Integer(3), new Double(7.3), "Delete2"},
                {new Date(), "D", new Integer(4), new Double(8.4), "Delete3"}
            };
    
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            JTable table = new JTable( model )
            {   [b]
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column)
                {
                    return getValueAt(0, column).getClass();
                }[/b]
            };
    
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
    
            //  Create button column
            ButtonColumn buttonColumn = new ButtonColumn(table, 4);
        }
    It runs great eventhough I did not use getColumnClass() method when setting the JTable's model.

    Why you did not use isCellEditable() in ButtonColumn class?
    Why most of the example in internet uses this?
    Also, Why did you use 2 different JButton in ButtonCloumn.java for cellEditor and cellRenderer, if it is only in one class and will 'be work as one'(i mean will show in same cell).

    Thanks for helping,
    geje
    Last edited by mine0926; 07-26-2010 at 03:56 AM.

  5. #5
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

    its a bit different with the link you gave me
    The link I gave you is the current code.

    Why you did not use isCellEditable() in ButtonColumn class?
    The isCellEditable(...) method is a method of the TableModel or the JTable, NOT a method of a renderer or an editor.

    Why most of the example in internet uses this?
    The default implementation for the DefaultTableModel is to make all cells editable. So you only need to override this method if you want to make some cells uneditable.

    Why did you use 2 different JButton in ButtonCloumn.java
    I don't remember the exact reason, but I guess it didn't work properly with only a single button.

    In the example you gave in the said forum I've seen that you use the method getColumnClass(), but in the blog you did not use it, why?
    The blog is a simple example that only uses Strings for the first two columns. The other example uses different Objects for each column so you need to tell the table what each column contains so it can choose the appropriate renderer/editor.

  6. #6
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    Thanks for the help, code and explanation. I really appreciated it.
    :)
    geje

Similar Threads

  1. JTable
    By BeeGee in forum Advanced Java
    Replies: 5
    Last Post: 04-28-2010, 05:29 PM
  2. Adding New JTable in JTable
    By anilkumar_vist in forum New To Java
    Replies: 0
    Last Post: 01-27-2010, 08:27 AM
  3. From txt to JTable.
    By ocean in forum New To Java
    Replies: 3
    Last Post: 10-17-2009, 09:30 PM
  4. Row Name In Jtable
    By SANDY_INDIA in forum AWT / Swing
    Replies: 1
    Last Post: 08-16-2008, 12:23 AM
  5. Replies: 2
    Last Post: 05-15-2008, 10:15 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •