Results 1 to 10 of 10
Like Tree1Likes
  • 1 Post By

Thread: JComboBox on Jtable

  1. #1
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default JComboBox on Jtable

    Hello everyone, im tired, and i can get any progress on a project im developing, im trying to use a JTable wich have different kind of data, some specific columns will display an Object i created my self wich represents some customers documentation, it have 3 possible states, "not applicable", "in order", "out of date". I was thinking of implementing this column with a JComboBox, originally had the idea, of using a custom combobox, in wich you could select the tag "not applicable", or a checkbox, wich you could select and check in case it is "in order" or leave unchecked if it is "out of date", but firist i preferred to test it with 3 tags in a combo box with the corresponding names, and make it change the background color to red in case it is "out of date", green if it is "in order" and yellow if it is "not applicable". Loading testing clients, i have no problem, at least on the beggining, but then i have a button, wich i would like to use to set this table to editable or not editable, and allow you to change the data from the different cells, then i start having problems, firist, when i click on the comboboxes, it loses the background color, and the font, and the whole column shows the Object info instead the combobox, untill i click on that cell, i can actually select any of the 3 components form the comboboxes, but it doesent update the background color, it remain as default, and if the combobox is "dropped down" and then click the button to edit, and make it not editable, this cells only remains editable.
    I dont know if im really tired, but its been 2 days im trying different stuffs to solve this, or even get different results but im stucked, i think is pretty much im missing something, or im "aiming to high".

    Here i post what i think is important from the code

    the renderer for the document renderer
    Java Code:
    package renderers;
    
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import datos.Documento;
    
    public class DocumentoRenderer extends JComboBox implements TableCellRenderer{
    	
    	public DocumentoRenderer(String[] items)
    	{
    		super(items);
    	}
    	public Component getTableCellRendererComponent(
    			JTable table, Object value,
    			boolean isSelected, boolean hasFocus,
    			int row, int column)
    	{	
    		Documento temp = (Documento)value;
    		if(isSelected && hasFocus){
    			this.setForeground(new Color(0,0,250));
    		}
    		else{
    			this.setForeground(new Color(0,0,0));
    		}
    		if(!temp.seAplica()){
    			this.setSelectedIndex(0);
    			this.setBackground(new Color(250,250,10));
    			
    		}else if(temp.estaPresentado()){
    			this.setSelectedIndex(1);
    			this.setBackground(new Color(10,250,10));
    		}else{
    			this.setSelectedIndex(2);
    			this.setBackground(new Color(250,10,10));
    		}
    
    		return this;
    	}
    }

    Action listener i use to set the whole table to editable or not editable

    Java Code:
    ...
    String[] temp = {"No aplica","Presentado","No Presentado"};
    ...
    
    	ActionListener setEditable = new ActionListener(){
    		public void actionPerformed(ActionEvent arg0){
    		
    			if(!flag){
    				inferior.setBackground(new Color(250,0,0));
    				flag = true;
    				model.editable(true);
    				table.getColumnModel().getColumn(7).setCellEditor(new DefaultCellEditor(new DocumentoRenderer(temp)));
    				table.getColumnModel().getColumn(8).setCellEditor(new DefaultCellEditor(new DocumentoRenderer(temp)));
    				table.getColumnModel().getColumn(13).setCellEditor(new DefaultCellEditor(new DocumentoRenderer(temp)));
    
    			}else{
    				inferior.setBackground(fondo);
    				flag = false;
    				model.editable(false);
    			}
    		}
    	};
    ...
    /*
    *Part of the code on te JPane where i add the Defaultrenderer to the Documento Object
    */
    ...
    		table.setDefaultRenderer(Documento.class, new DocumentoRenderer(temp));
    ...
    and finally my own implementatin of the TableModel (dont hate me too much im learning)

    Java Code:
    package carpetacomitentes;
    
    import java.util.Iterator;
    import java.util.Vector;
    
    import javax.swing.table.AbstractTableModel;
    
    import datos.Comitente;
    
    class ModeloDeTabla extends AbstractTableModel{
    	private String[] nombres = {"Nş comitente","fecha apertura","oficial de cuenta", "nombre y apellido","Datos pers.","inf.patr.","inf. fin.","DDJJ PEP","auto.","perfil cuenta","perfil inv.","DNI","CUIT/CUIL","Cons. ins.","impuestos","DDJJ Gcias", "recibo sueldo","Rofex", "MaTBA"};
    	private Object[][] datos ={};
    	private static boolean esEditable = false;
    	
    	public ModeloDeTabla(Vector<Comitente> comitentes, boolean fisico){
    		
    		datos = new Object[comitentes.indexOf(comitentes.lastElement())+1][nombres.length];
    		if(fisico){
    			Iterator<Comitente> it = comitentes.iterator();
    			//contador que determina la fila
    			int i=0;
    			while(it.hasNext()){
    				Comitente temp = it.next();
    				cargaComitente(temp, i);
    				i++;
    			}
    		}
    		
    	}
    	
    	private void cargaComitente(Comitente comitente, int fila){
    		 
    		
    		datos[fila][0] = comitente.getNumComitente(); //numero comitente
    		datos[fila][1] = comitente.getFechaApertura(); //fecha de apertura de cuenta
    		datos[fila][2] = comitente.getAgente().getNombre(); // nombre del agente del comitente 
    		datos[fila][3] = comitente.getNombre(); //nombre del comitente
    		/*
    		 * Parte de ficha de comitentes
    		 */
    		datos[fila][4] = comitente.getFichaComitente().getDatos(); //si tiene presentado los datos personales
    		datos[fila][5] = comitente.getFichaComitente().getInfPatrimonial();//si presento informacion patrimonial
    		datos[fila][6] = comitente.getFichaComitente().getInfFinanciera();//si presento informacion financiera
    		datos[fila][7] = comitente.getFichaComitente().getDecJurPEP();//si presento declaracion jurada de persona politicamente expuesta, puede no aplicar
    		datos[fila][8] = comitente.getFichaComitente().getAutorizaciones();//autorizacion
    		datos[fila][9] = comitente.getFichaComitente().getPerfilCue();//perfil cuenta
    		datos[fila][10] = comitente.getFichaComitente().getPerfilInv();//perfil inversor
    		/*
    		 * Parte de documentacion
    		 */
    		datos[fila][11] = comitente.getDocumentacionFisica().getDNI();//DNI
    		datos[fila][12] = comitente.getDocumentacionFisica().getCuit();//CUIT/CUIL
    		datos[fila][13] = comitente.getDocumentacionFisica().getConstancia();//constancia inscripcion
    		datos[fila][14] = comitente.getDocumentacionFisica().getImpuesto();//impuestos
    		datos[fila][15] = comitente.getDocumentacionFisica().getDeclaracion();//DJJ ganancias
    		datos[fila][16] = comitente.getDocumentacionFisica().getRecibo();//recibo de sueldo
    		/*
    		 * Parte de Convenios
    		 */
    		datos[fila][17] = comitente.getConvenio().getRofex();//rofex
    		datos[fila][18] = comitente.getConvenio().getMatba();//maba
    		
    		
    	}
    	public static void editable(boolean b){
    		esEditable = b;
    	}
    	public boolean isCellEditable(int row, int col)
        { 
    		return esEditable; 
        }
    	public int getColumnCount() {
    		return nombres.length;
    	}
    	public int getRowCount() {
    		return datos.length;
    	}
    	public Object getValueAt(int fila, int col) {
    		return datos[fila][col];
    	}
    	public String getColumnName(int col) {
            return nombres[col];
        }
    	public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
        }
    	public void setValueAt(Object value, int row, int col) {
    	        datos[row][col] = value;
    	        fireTableCellUpdated(row, col);
    	}
    }

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

    Default Re: JComboBox on Jtable

    Consider condensing the text of your question a bit, checking your question for spelling and grammar problems or use of non-standard abbreviations (remember, many of us here do not speak English as a native language), and creating a small compilable and runnable program that demonstrates your problem. This will make it *much* easier for us to help you.

  3. #3
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default Re: JComboBox on Jtable

    Yes, i'm sorry, english is not my native languaje either, i learned it from the internet, so is the best i can do without a spell check program, i'm working on the small compilable program, i will try to upload it soon.

  4. #4
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default Re: JComboBox on Jtable

    Ok, here we go again, i did not have enough time yesterday to make a compilable test, and i was hoping my mistakes were a frecuent mistake, so anyone with experience would be able to correct me faster.
    So, the firist time i compile and run this program, it show me the data as i want to, especially the comboboxes, but once i click on the "edit" button and try to drop down the list of the comboboxes, the problems start to show, if i click on the firist element of each column, it lose the background, and if then i click on other cell the entire column is shown as if it had no render.
    Also, if the firist cell i click, after compiling and running the program, and click on the "edit" button, is any other than the firist cell on any column, and try to select other value on the combobox, it just trhow an exception and the program stop working.


    Java Code:
    package Pruebas;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    
    public class Prueba extends JFrame{
    
    	static Prueba test;
    	
    	private Color fondo = new Color(150,150,150); //default background color for the button container panel
    	String[] temp = {"Not applicable","In order","Out of date"}; //list of states the combobox on the table can assume
    	boolean flag = false;
    	private MyModel model;
    	private JPanel inferior;
    	private JPanel tablePanel;
    	private JScrollPane scrollPane;
    	private JTable table;
    	private JButton btnEdit;
    	private JButton btnClose;
    	
    	public static void main(String[] args) {
    		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    		 
    		test = new Prueba();
    		// Determine the new location of the window
    		int w = test.getSize().width;
    		int h = test.getSize().height;
    		int x = (dim.width-w)/2;
    		int y = (dim.height-h)/2;
    		 
    		// Move the window
    		test.setLocation(x, y);
    		test.setVisible(true);
    	}
    	Prueba(){
    		setTitle("Testing window");
    		setSize(200, 200);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		JPanel topPanel = new JPanel();
    		topPanel.setLayout(new BorderLayout());
    		getContentPane().add( topPanel );
    		
    		/*
    		 * Bottom panel where i will add the buttons
    		 */
    		inferior = new JPanel();
    		inferior.setBackground(fondo);
    		inferior.setLayout(new FlowLayout());
    		/*
    		 * Main panel, wich will contain the table, and the bottom panel with the buttons
    		 */
    		tablePanel = new JPanel();
    		tablePanel.setLayout(new BorderLayout());
    		tablePanel.setBackground(fondo);
    		
    		/*
    		 * Setting up the model using my own Model class, and apllying it to a Jtable,
    		 * Setting some minor importance stetic changes to the table
    		 */
    		model = new MyModel();
    		table = new JTable(model);
    		table.getTableHeader().setFont(new Font("SansSerif", Font.ITALIC, 10));
    		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    		scrollPane = new JScrollPane(table);
    		/*
    		 * Here i'm Setting the Renderers for the two kind of data, boolean, and Documento
    		 * Using created Renderers
    		 */
    		table.setDefaultRenderer(Documento.class, new DocumentoRenderer(temp));
    		table.setDefaultRenderer(Boolean.class, new MiBoolRender());
    		/*
    		 * adding the scrollpane to the Frame
    		 */
    		scrollPane.setBounds(10, 11, 200, 200);
    		topPanel.add(scrollPane, BorderLayout.CENTER);
    		
    		btnClose = new JButton("close");
    		btnClose.setBounds(10, 10, 89, 23);
    		btnClose.addActionListener(close);
    		inferior.add(btnClose, FlowLayout.LEFT);
    		
    		btnEdit = new JButton("Edit");
    		btnEdit.setBounds(50, 10, 90, 23);
    		btnEdit.addActionListener(setEditable);
    		inferior.add(btnEdit, FlowLayout.CENTER);
    		
    		topPanel.add(inferior, BorderLayout.SOUTH);
    		
    	}
    	/*
    	 * This is the ActionListener i would like to make work, making the table's cell editable or not
    	 */
    	ActionListener setEditable = new ActionListener(){
    		public void actionPerformed(ActionEvent arg0){
    		
    			if(!flag){
    				inferior.setBackground(new Color(250,0,0));
    				flag = true;
    				model.editable(true);
    				table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new DocumentoRenderer(temp)));
    				table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new DocumentoRenderer(temp)));
    				table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(new DocumentoRenderer(temp)));
    
    			}else{
    				inferior.setBackground(fondo);
    				flag = false;
    				model.editable(false);
    			}
    		}
    	};
    	/*
    	 * action listener added to the Close button to close the application
    	 */
    	ActionListener close = new ActionListener(){
    		public void actionPerformed(ActionEvent arg0){
    			dispose();
    		}
    	};
    
    
    }
    /**
     * Class for the object Documento (document in english), used to create Objects of that type.
     */
    class Documento {
    	boolean presentado;
    	boolean aplica;
    	/**
    	 * Empty constructor
    	 */
    	public Documento(){
    		
    	}
    	/**
    	 * Constructor i will use to instance the Documento objects
    	 * @param aplica
    	 * @param pres
    	 */
    	public Documento(boolean aplica, boolean pres){
    		/*
    		 * it shouldn't assume aplica = false and presentado = true.
    		 */
    		
    		if(aplica){
    			aplica = true;
    			presentado = pres;
    		}else{
    			aplica = false;
    			presentado = false;
    		}
    	}
    	/*
    	 * Methods to obtain and set the booleans values on the instanced object
    	 */
    	public boolean seAplica(){
    		return aplica;
    	}
    	public boolean estaPresentado(){
    		return presentado;
    	}
    	public void setAplica(boolean a){
    		aplica = a;
    		if(!a){
    			presentado = false;
    		}
    	}
    	public void setPresentado(boolean p){
    		presentado = p;
    	}
    }
    /**
     * Class to implement my own model of table
     */
    class MyModel extends AbstractTableModel{
    
    	private static final long serialVersionUID = 1L;
    	private String[] header = {"comboBox1","comboBox2","comboBox3","CheckBox"};
    	private Object[][] data = new Object[4][4];
    	private static boolean esEditable = false;
    	/*
    	 * MyModel constructor, it just calls the method to populate the table with random data,
    	 * this table will contain 3 columns of "Documento" objects, wich i will render on the table
    	 * as a JComboBox, with the DocumentoRenderer, the other column is a JCheckBox i will render
    	 * this last one with MiBoolRenderer.
    	 */
    	public MyModel(){
    		data = createData();
    	}
    	public Object[][] createData(){
    
    		/*
    		 * Random data
    		 */
    		Documento firist = new Documento(true, false);
    		Documento second = new Documento(false,false);
    		Documento third = new Documento (true,true);
    		
    		data[0][0] = firist;
    		data[0][1] = second;
    		data[0][2] = third;
    		data[0][3] = true;
    				
    		firist = new Documento(false, false);
    		second = new Documento(false,false);
    		third = new Documento (true,false);
    		
    		data[1][0]= firist;
    		data[1][1]= second;
    		data[1][2] = third;
    		data[1][3] = false;
    		
    		firist = new Documento(true, true);
    		second = new Documento(false,true);
    		third = new Documento (true,false);
    		
    		data[2][0]= firist;
    		data[2][1]= second;
    		data[2][2] = third;
    		data[2][3] = false;
    		
    		firist = new Documento(true, false);
    		second = new Documento(true,false);
    		third = new Documento (true,true);
    		
    		data[3][0]= firist;
    		data[3][1]= second;
    		data[3][2] = third;
    		data[3][3] = true;
    		
    		return data;
    	}
    	@Override
    	public int getColumnCount() {
    		return header.length;
    	}
    
    	@Override
    	public int getRowCount() {
    		return data.length;
    	}
    
    	@Override
    	public Object getValueAt(int row, int col) {
    		return data[row][col];
    	}
    	public String getColumnName(int col) {
            return header[col];
        }
    	public Class getColumnClass(int c) {
    		
    		return getValueAt(0, c).getClass();
              
        }
    	public void setValueAt(Object value, int row, int col) {
    	        data[row][col] = value;
    	        fireTableCellUpdated(row, col);
    	}
    	/*
    	 * Methods whom enables or disables the edition on the table data
    	 */
    	public static void editable(boolean b){
    		esEditable = b;
    	}
    	public boolean isCellEditable(int row, int col)
        { 
    		return esEditable; 
        }
    }
    /**
     * Render for the Documento type Object
     */
    class DocumentoRenderer extends JComboBox implements TableCellRenderer{
    	
    	public DocumentoRenderer(String[] items)
    	{
    		super(items);
    	}
    	public Component getTableCellRendererComponent(
    			JTable table, Object value,
    			boolean isSelected, boolean hasFocus,
    			int row, int column)
    	{			
    		Documento temp = (Documento) value;
    		/*
    		 * If is selected and focused the cell set the foreground colors
    		 */
    		if(isSelected && hasFocus){
    			this.setForeground(new Color(0,0,250));
    		}
    		else{
    			this.setForeground(new Color(0,0,0));
    		}
    		/*
    		 * Part of the program i think is giving me troubles, when firist loaded the data is shown
    		 * as i want to, but once i click on the Edit button and try to change the data, 
    		 * i start having problems
    		 */
    			if(!temp.seAplica()){
    				this.setSelectedIndex(0);
    				this.setBackground(new Color(250,250,10));
    			
    			}else if(temp.estaPresentado()){
    				this.setSelectedIndex(1);
    				this.setBackground(new Color(10,250,10));
    			}else{
    				this.setSelectedIndex(2);
    				this.setBackground(new Color(250,10,10));
    			}
    		
    		return this;
    	}
    }
    /**
     * Render for Booleans
     */
    class MiBoolRender extends JCheckBox implements TableCellRenderer{
    
    	@Override
    	public Component getTableCellRendererComponent(JTable table, Object value,
    			boolean isSelected, boolean hasFocus, int row, int column) {
    		
    		Boolean b = (Boolean) value;
    		
    		this.setHorizontalAlignment(CENTER);
    		/*
    		 * Checking and un-Checking the CheckBox, setting the background in green or red.
    		 */
    		if(b){
    			this.setBackground(new Color(10,255,10));
    			this.setSelected(true);
    		}else{
    			this.setSelected(false);
    			this.setBackground(new Color(255,10,10));
    		}
    		
    		return this;
    	}
    	/*
    	public void setValueAt(Object value, int row, int col){
    		if((Boolean)value){
    			this.setSelected(false);
    		}else{
    			this.setSelected(true);
    		}
    	}
    	*/
    }

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

    Default Re: JComboBox on Jtable

    I'm still trying to work this out. So far I have code that is not quite working....

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    
    public class Prueba2 extends JPanel {
       public static final String[] temp = { "Not applicable", "In order",
             "Out of date" };
       private MyModel2 model = new MyModel2();
       private JToggleButton editableBtn = new JToggleButton(new EditableAction(
             "Editable", model));
       private DocumentoRenderer2 documentoRenderer = new DocumentoRenderer2(temp);
       private ColorCheckBoxRenderer colorCheckBoxRenderer = new ColorCheckBoxRenderer();
       private JTable table = new JTable(model) {
          public javax.swing.table.TableCellRenderer getCellRenderer(int row,
                int column) {
             if (column == getColumnCount() - 1) {
                // return super.getCellRenderer(row, column);
                return colorCheckBoxRenderer;
             }
             return documentoRenderer;
          };
       };
    
       public Prueba2() {
          JPanel btnPanel = new JPanel();
          btnPanel.add(editableBtn);
    
          DocumentoEditor documentoEditor = new DocumentoEditor(temp);
          TableColumnModel tableColumnModel = table.getColumnModel();
          for (int i = 0; i < table.getColumnCount() - 2; i++) {
             TableColumn column = tableColumnModel.getColumn(i);
             column.setCellEditor(documentoEditor);
          }
    
          setLayout(new BorderLayout());
          add(new JScrollPane(table));
          add(btnPanel, BorderLayout.SOUTH);
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("Prueba2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new Prueba2());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    class MyModel2 extends AbstractTableModel {
    
       private static final long serialVersionUID = 1L;
       private String[] header = { "Documento 1", "Documento 2", "Documento 3",
             "CheckBox" };
       private Object[][] data = new Object[4][4];
       private boolean editable = false;
    
       public MyModel2() {
          data = createData();
       }
    
       public Object[][] createData() {
    
          /*
           * Random data
           */
          Documento2 first = new Documento2(true, false);
          Documento2 second = new Documento2(false, false);
          Documento2 third = new Documento2(true, true);
    
          data[0][0] = first;
          data[0][1] = second;
          data[0][2] = third;
          data[0][3] = true;
    
          first = new Documento2(false, false);
          second = new Documento2(false, false);
          third = new Documento2(true, false);
    
          data[1][0] = first;
          data[1][1] = second;
          data[1][2] = third;
          data[1][3] = false;
    
          first = new Documento2(true, true);
          second = new Documento2(false, true);
          third = new Documento2(true, false);
    
          data[2][0] = first;
          data[2][1] = second;
          data[2][2] = third;
          data[2][3] = false;
    
          first = new Documento2(true, false);
          second = new Documento2(true, false);
          third = new Documento2(true, true);
    
          data[3][0] = first;
          data[3][1] = second;
          data[3][2] = third;
          data[3][3] = true;
    
          return data;
       }
    
       @Override
       public int getColumnCount() {
          return header.length;
       }
    
       @Override
       public int getRowCount() {
          return data.length;
       }
    
       @Override
       public Object getValueAt(int row, int col) {
          return data[row][col];
       }
    
       public String getColumnName(int col) {
          return header[col];
       }
    
       public Class getColumnClass(int c) {
    
          return getValueAt(0, c).getClass();
    
       }
    
       public void setValueAt(Object value, int row, int col) {
          data[row][col] = value;
          fireTableCellUpdated(row, col);
       }
    
       /*
        * Methods whom enables or disables the edition on the table data
        */
       public void setEditable(boolean editable) {
          this.editable = editable;
       }
    
       public boolean isCellEditable(int row, int col) {
          return editable;
       }
    }
    
    class Documento2 {
       boolean presentado;
       boolean aplica;
    
       /**
        * Empty constructor
        */
       public Documento2() {
    
       }
    
       public Documento2(boolean aplica, boolean pres) {
          if (aplica) {
             aplica = true;
             presentado = pres;
          } else {
             aplica = false;
             presentado = false;
          }
       }
    
       public boolean seAplica() {
          return aplica;
       }
    
       public boolean estaPresentado() {
          return presentado;
       }
    
       public void setAplica(boolean a) {
          aplica = a;
          if (!a) {
             presentado = false;
          }
       }
    
       public void setPresentado(boolean p) {
          presentado = p;
       }
    
       @Override
       public String toString() {
          return "Documento2 [presentado=" + presentado + ", aplica=" + aplica
                + "]";
       }
       
       
    }
    
    class DocumentoEditor extends AbstractCellEditor implements TableCellEditor {
       private JComboBox<String> comboBox;
       
       public DocumentoEditor(String[] items) {
          comboBox = new JComboBox<String>(items);
       }
    
       @Override
       public Object getCellEditorValue() {
          int index = comboBox.getSelectedIndex();
          boolean aplica = false;
          boolean pres = false;
          switch (index) {
          case 1:
             aplica = true;
             pres = true;
             break;
          case 2:
             aplica = true;
             pres = false;
             break;
    
          }
          Documento2 doc2 = new Documento2(aplica, pres);
          System.out.println(doc2);
          
          return doc2;
       }
    
       @Override
       public Component getTableCellEditorComponent(JTable table, Object value,
             boolean isSelected, int row, int column) {
          Documento2 doc2 = (Documento2)value;
          if (!doc2.seAplica()) {
             comboBox.setSelectedIndex(0);
          } else if (doc2.estaPresentado()) {
             comboBox.setSelectedIndex(1);
          } else {
             comboBox.setSelectedIndex(2);
          }
          return comboBox;
       }
    
    
    }
    
    class DocumentoRenderer2 extends DefaultTableCellRenderer {
       private String[] items;
    
       public DocumentoRenderer2(String[] items) {
          this.items = items;
       }
    
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value,
             boolean isSelected, boolean hasFocus, int row, int column) {
    
          Documento2 temp = (Documento2) value;
    
          if (isSelected && hasFocus) {
             this.setForeground(new Color(0, 0, 250));
          } else {
             this.setForeground(new Color(0, 0, 0));
          }
    
          if (!temp.seAplica()) {
             value = items[0];
             this.setBackground(new Color(250, 250, 10));
    
          } else if (temp.estaPresentado()) {
             value = items[1];
             this.setBackground(new Color(10, 250, 10));
          } else {
             value = items[2];
             this.setBackground(new Color(250, 10, 10));
          }
    
          DefaultTableCellRenderer superRenderer = (DefaultTableCellRenderer) super
                .getTableCellRendererComponent(table, value, isSelected, hasFocus,
                      row, column);
    
          return this;
       }
    
    }
    
    class ColorCheckBoxRenderer extends JPanel implements TableCellRenderer {
       private static final Color SELECTED_COLOR = Color.green;
       private static final Color UNSELECTED_COLOR = Color.red;
       private JPanel panel = new JPanel();
       private JCheckBox checkBox = new JCheckBox();
    
       public ColorCheckBoxRenderer() {
          checkBox.setOpaque(false);
          panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
          panel.add(Box.createHorizontalGlue());
          panel.add(checkBox);
          panel.add(Box.createHorizontalGlue());
       }
    
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value,
             boolean isSelected, boolean hasFocus, int row, int column) {
          checkBox.setSelected((Boolean) value);
          Color bg = ((Boolean) value).booleanValue() ? SELECTED_COLOR
                : UNSELECTED_COLOR;
          panel.setBackground(bg);
          return panel;
       }
    
    }
    
    class EditableAction extends AbstractAction {
       private MyModel2 model;
    
       public EditableAction(String name, MyModel2 model) {
          super(name);
          this.model = model;
       }
    
       @Override
       public void actionPerformed(ActionEvent e) {
          JToggleButton tglBtn = (JToggleButton) e.getSource();
          model.setEditable(tglBtn.isSelected());
    
       }
    }

  6. #6
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default Re: JComboBox on Jtable

    I don't know if you did not realize the "Documento" values in the table are (false, false), so them all are "not apllicable", however that mistake have origin in my Testing program , is a problem on the assignation inside the Documento(boolean, boolean) constructor.

    Java Code:
    ...
    
    	/**
    	 * Constructor i will use to instance the Documento objects
    	 * @param aplica
    	 * @param pres
    	 */
    	public Documento2(boolean aplica, boolean pres){
    		/*
    		 * it shouldn't assume aplica = false and presentado = true.
    		 */
    		
    		if(aplica){
    			this.aplica = true;
    			presentado = pres;
    		}else{
    			this.aplica = false;
    			presentado = false;
    		}
    	}
    ...
    It is not a big problem, but, i found it while i was checking your program, i'm trying to figure out the changes you made, providing me new posibilities, like the toggle button you used, i like it better.

  7. #7
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default Re: JComboBox on Jtable

    Wow!, in fact making that change, almost solve the whole problem in your implementation. It was my fault, since when i tryied to adapt my original program, the constructor i had there used other parameter names, i changed them in the new program version.

  8. #8
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default Re: JComboBox on Jtable

    Thank you a lot, you helped me, summarizing: i needed to add the CellEditor, extending the AbstractCellEitor, and implementing the TableCellEditor. And the toggle Button is usefull. Still, i'm trying to find out how to "de-select" the current comboBox when i click and "un-toggle" the Edit button, since if i "un-toggle" this button, the selected combobox remains "editable" until i take away the focus.

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

    Default Re: JComboBox on Jtable

    Some changes to stop editing when focus is lost:

    Java Code:
       public Prueba2() {
          JPanel btnPanel = new JPanel();
          btnPanel.add(editableBtn);
    
          DocumentoEditor documentoEditor = new DocumentoEditor(temp);
          TableColumnModel tableColumnModel = table.getColumnModel();
          for (int i = 0; i < table.getColumnCount() - 1; i++) {
             TableColumn column = tableColumnModel.getColumn(i);
             column.setCellEditor(documentoEditor);
          }
          
          // add this to all selection of a single cell
          table.setColumnSelectionAllowed(true);
          
          // add this to allow the cell editor to stop when focus is lost
          table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    
          setLayout(new BorderLayout());
          add(new JScrollPane(table));
          add(btnPanel, BorderLayout.SOUTH);
       }

  10. #10
    GermánS is offline Member
    Join Date
    Feb 2012
    Posts
    10
    Rep Power
    0

    Default Re: JComboBox on Jtable

    Oh thats great, i have to sit and read that putClientProperty method Docummentation.
    Fubarable likes this.

Similar Threads

  1. Showing different values in JComboBox inside JTable
    By d3n1s in forum Advanced Java
    Replies: 2
    Last Post: 05-02-2011, 09:25 PM
  2. Adding JComboBox type column to the JTable ??
    By Stephen Douglas in forum New To Java
    Replies: 2
    Last Post: 04-10-2010, 04:03 PM
  3. Replies: 2
    Last Post: 12-10-2009, 02:58 PM
  4. JComboBox in Jtable
    By maneesh in forum AWT / Swing
    Replies: 3
    Last Post: 12-09-2009, 09:37 PM
  5. JComboBox in JTable and Cant get Focus...
    By markw8500 in forum New To Java
    Replies: 1
    Last Post: 03-30-2009, 12:35 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
  •