JTable with JCheckbox problems

Ok so I have a couple of questions. I have a JTable with a column represented as a checkbox.
1. If I put the checkbox column as the first in the table, the rest of the cells are blank/null. Any idea what the reason is?
2. What is the best workaround to having draggable columns, meaning icons/checkboxes don't render if you move the columns around?
3. Does anyone have some links to good resources on JTables and things like custom components in them. I have googled but don't get many good links so would appreciate any help
Code snippet as follows:
public class ClobberTableCellRenderer implements TableCellRenderer
private JPanel renderPanel = new JPanel(new BorderLayout());
private JLabel renderLbl = new JLabel("");
private JCheckBox checked = new JCheckBox();
private Icon successIcon;
private Icon errorIcon;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
String columnName = table.getModel().getColumnName(column);
if (value == null)
return null;
else if ("Status".equals(columnName) && "ok".equals(value))
renderLbl.setIcon(successIcon);
renderLbl.setText("");
renderPanel.remove(checked);
else if ("Status".equals(columnName) && "error".equals(value))
renderLbl.setIcon(errorIcon);
renderLbl.setText("");
renderPanel.remove(checked);
else if ("Active".equals(columnName))
renderLbl.setText("");
renderPanel.add(checked);
renderPanel.setBackground(Color.white);
else
renderLbl.setHorizontalAlignment(value instanceof Date || value instanceof Number ? JLabel.RIGHT : JLabel.LEFT);
renderLbl.setIcon(null);
renderLbl.setText(value instanceof Date ? df.format((Date)value) : value.toString());
renderLbl.setToolTipText(null);
renderPanel.setToolTipText(null);
renderPanel.remove(checked);
if (isSelected)
renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.selectionBackground"));
else
renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.background"));
return renderPanel;
}

Hi :) I have also worked on JTables and JCheckBoxes before. This article
helped me a lot: http://www-128.ibm.com/developerworks/java/library/j-jtable/

Similar Messages

  • Problem with JTable with JCheckBox as Header

    Hi,
    We have a JCheckBox as JTable Header. And respective data in that column also check boxes. For data check boxes, just i am sending Boolean object to object[][] data array. I am getting check Boxes as data components.
    For Header, i have create a TableRender object which is returning JCheckBox.
    Here my problem is,
    1) When i select a Header check box, all the check boxes are getting selected.
    2) Now we can reselect an data Check Box. When i reselect any data checkBox, Header CheckBox should be reselected. This is not happening. I was tried lot. Can any body give a solution to solve this problem.
    Please .... Please ...
    Thanks
    Mohan

    just call this method with null param on the JTable
    table.setTableHeader(null);
    cheers
    krishna

  • Detecting clicked column in JTable (with JCheckBox in column)

    I am struggling with something that seems like it should be so simple, but it doesn't work as I expect;
    I have a table with 5 columns, the 5th column is a CheckBox. What I need to do is detect when the 5th column changes, ie. the check box is clicked;
    If I use a MouseListener on the table, and derive the table from the event, the column that I get back from getSelectedColumn() is -1, which is not conclusive. I assume this is because clicking the check box is not actually selecting the column.
    I implemented a TableModelListener as follow;
    tableModel.addTableModelListener(new TableModelListener()
    public void tableChanged(TableModelEvent e)
    System.out.println("Changed Column is " + e.getColumn() + " " + e.getFirstRow());
    This seems to do the same as before, and gives a first row of 0 and selected column of -1. Once again inconclusive.
    The cell as I say is rendered as a JCheckBox, the data in the table model obviously being Boolean.
    Can anyone suggest how I can determine if my column with a Check Box in has been clicked, and if so, which Row? (I have thought about overriding JCheckBox, but this seems more work than necessary)
    Thanks in anticipation

    You need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html]
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on
    the information provided.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting] so the posted code retains its original formatting.

  • JTable with JCheckBox

    Hi,
    Does anyone know how to make the selection on check boxes in a JTable limited to one?
    Currently the check box column in my JTable allow for multiple selection, but I want to make it so that only one check box can be selected at a time.
    thanks

    maybe you can make a checker??
    for instance: checkbox one is clicked
    I click at checbox three and my programm is checking every checkbox on his selected value, if that value is truu then you set that value to false .... and at the end if every check box is false you set the one you clicked to true....
    maybe you can do this at once in a for or while loop or something of in a switch statement

  • Problem with JCheckBox in a JTable

    Hello,
    I have a JTable with JCheckBox as Editor for boolean values.
    I added a ListSelectionListener on that JTable.
    My problem is :
    when I click on a cell which have a JCheckBoxEditor, there is only one event generated : the one which unselect the row previously selected.
    So i can't answer the selection.
    what could have append ?
    thanks a lot.
    fleur.

    hi,
    I have no custom editor for this table.
    here is my code :
    public VDEComposant(Locale langue,InterfaceModeleur listener,Composant composant,int largeur) {
    super(langue,listener,largeur);
    this.setLayout(new BorderLayout());
    _modele=listener.getModele();
    _composantCourant=composant;
    this.addComposantsListener((ComposantsListener)listener.getGestionnaire());
    construitBarreOutils();
    setNbLigne1(this.listeComposant(composant).size());
    int m=0;
    if (composant==Composant.COMPOSANT){
    _donCompPereApTM=this.creeModeleDonnee1(composant);
    _donCompPereApTM.addTableModelListener(this);
    setTableau1(new JTable(_donCompPereApTM));
    m=1;
    else{
    if (composant.getPere()==Composant.COMPOSANT){
    _donCompApTM=creeModeleDonnee1(composant);
    _donCompApTM.addTableModelListener(this);
    setTableau1(new JTable(_donCompApTM));
    else {
    _donCompUtTM=creeModeleDonnee1(composant);
    _donCompUtTM.addTableModelListener(this);
    setTableau1(new JTable(_donCompUtTM));
    getTableau1().addMouseListener(((OngletDonnees)((OngletDonnees)getIHM().getOngletDonnees())).getOngletComposants());
    MultipleComboBoxCellEditor editor = new MultipleComboBoxCellEditor(new JComboBox());
    getTableau1().getColumnModel().getColumn(4+m).setCellEditor(editor) ;
    getTableau1().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    getTableau1().getSelectionModel().addListSelectionListener(this);
    Dimension d1 = new Dimension(_largeur, getNbLigne1()*16);
    JScrollPane sc1 = new JScrollPane(getTableau1());
    sc1.setViewportView(getTableau1());
    if((composant.getPere()!=null)&&(composant.getPere()!=Composant.COMPOSANT)){
    this.add(_outils,BorderLayout.NORTH);
    String s="";
    if((composant.getPere()==null)||(composant.getPere()==Composant.COMPOSANT)){
    String sc="";
    if(composant==Composant.COMPOSANT_IMAGE){
    sc=" "+_ressources.getString("images");
    if(composant==Composant.COMPOSANT_LINEAIRE){
    sc=" "+_ressources.getString("lineaires");
    if(composant==Composant.COMPOSANT_METAD){
    sc=" "+_ressources.getString("lotdonnees");
    if(composant==Composant.COMPOSANT_NGS){
    sc=" "+_ressources.getString("nongraphiques");
    if(composant==Composant.COMPOSANT_SURFACIQUE){
    sc=" "+_ressources.getString("surfaciques");
    if(composant==Composant.COMPOSANT_SYMBOLIQUE){
    sc=" "+_ressources.getString("symboliques");
    s=_ressources.getString("liste_composant")+sc;
    else{
    s=_ressources.getString("description_composant");
    JLabel lab = new JLabel(s,JLabel.CENTER);
    JPanel inter = new JPanel(new GridLayout(1,1));
    inter.add(lab);
    inter.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createEtchedBorder()));
    Box boite1 = Box.createVerticalBox();
    boite1.add(inter);
    boite1.add(sc1);
    _inter.add(boite1);
    //ajout du deuxieme tableau
    _donAttCompTM=this.creeModeleDonnee2(composant);
    _donAttCompTM.addTableModelListener(this);
    setTableau2(new JTable(_donAttCompTM));
    getTableau2().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    getTableau2().getSelectionModel().addListSelectionListener(this);
    getTableau2().addMouseListener(((OngletDonnees)((OngletDonnees)getIHM().getOngletDonnees())).getOngletComposants());
    //ComboBox pour saisir le type de l'attribut
    _typeA = new JComboBox();
    _typeA.addItem(TypeEtendu.DATE.getNom());
    _typeA.addItem(TypeEtendu.DOMAINE.getNom());
    _typeA.addItem(TypePrimitif.ENTIER.getNom());
    _typeA.addItem(TypePrimitif.LOGIQUE.getNom());
    _typeA.addItem(TypePrimitif.REEL.getNom());
    _typeA.addItem(TypePrimitif.TEXTE.getNom());
    (getTableau2().getColumnModel().getColumn(3)).setCellEditor(new DefaultCellEditor(_typeA));;
    //renderer pour la colonne des nom qui indique en gras l'attribut identifiant
    getTableau2().getColumnModel().getColumn(1).setCellRenderer(new AttributTableCellRenderer(_composantCourant));
    Dimension d2 = new Dimension(_largeur ,(getNbLigne2()*16));
    JScrollPane sc2 = new JScrollPane(getTableau2());
    sc2.setViewportView(getTableau2());
    _inter.createVerticalStrut(16);
    inter = new JPanel(new GridLayout(1,1));
    lab = new JLabel(_ressources.getString("attributs"),JLabel.CENTER);
    inter.add(lab);
    inter.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(),BorderFactory.createEtchedBorder()));
    Box boite2=Box.createVerticalBox();
    boite2.add(inter);
    boite2.add(sc2);
    _inter.add(boite2);
    if((composant.getPere()!=null)&&(composant.getPere()!=Composant.COMPOSANT)){
    this.add(_inter,BorderLayout.CENTER);
    else{
    this.add(_inter,BorderLayout.NORTH);
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm =(ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    else {
    int ligneSel = lsm.getMinSelectionIndex();
    if(e.getSource()==getTableau2().getSelectionModel()){
    String alias = (String) _donAttCompTM.getValueAt(ligneSel,1);
    attribut = composantCourant.getAttribut(alias);
    else if(e.getSource()==getTableau1().getSelectionModel()){
    VectorTableModel vtm = null;
    int i = 0;
    if(_donCompApTM != null){
    vtm = _donCompApTM;
    if(_donCompPereApTM != null){
    vtm = _donCompPereApTM;
    i =1;
    if(vtm != null){
    String alias = (String) vtm.getValueAt(ligneSel,i);
    composantSelectionne= modele.getComposant(alias);
    else{
    composantSelectionne=composantCourant;
    I hope it make sens,
    thanks.

  • JTable with a JCheckBox in a header column

    Hi everybody,
    I have implemented a JTable with a JCheckbox in one of the header columns. For this I have used the following code from the Internet for rendering the table cell:
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent;
         protected int column;
         protected boolean mousePressed = false;
         public CheckBoxColumnHeader(ItemListener itemListener) {   
              rendererComponent = this;
              rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (table != null) {     
                   JTableHeader header = (ExtendedJTableHeader)table.getTableHeader();
                   if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());
                        rendererComponent.setBackground(header.getBackground());
                        rendererComponent.setFont(header.getFont());
                        header.addMouseListener(rendererComponent);
              setColumn(column);
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));
              return rendererComponent;
    From a technical point of view, the checkbox works as expected. However, I have problems with the graphical layout of the checkbox in the header column:
    1) The checkbox seems to be bigger than the height of the header column. It overlays the border lines of the table. When I increase the preferred size of the header row, the checkbox also increases its size and still overlays the table border lines.
    2) The checkbox has a diffferent background shading than the other columns in the header.
    Any help for solving these two layout problems are greatly appreciated.
    Thanks, Walter

    Hi,
    here is now the complete code
    package main;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Arrays;
    import java.util.Vector;
    import javax.swing.table.*;
    * <p>�berschrift: </p>
    * <p>Beschreibung: </p>
    * <p>Copyright: Copyright (c) 2007</p>
    * <p>Organisation: </p>
    * @author unbekannt
    * @version 1.0
    public class MainFrame extends JFrame {
         JTable table3;
         JScrollPane scp3; 
      //Den Frame konstruieren
      public MainFrame() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Initialisierung der Komponenten
      private void jbInit() throws Exception  {
        this.setSize(new Dimension(500, 320));
        this.setTitle("Action List");
        Vector<Object> rowData = new Vector<Object>();
        for (int i=0; i<3; i++) {
             Vector<Object> colData = new Vector<Object>(Arrays.asList("Data R" + i + "C0", "Data R" + i + "C1", "Data R" + i +"C2", (i%2 == 0) ? Boolean.TRUE : Boolean.FALSE));
             rowData.add(colData);
        Vector<Object> hdr = new Vector<Object>(Arrays.asList("Column 0", "Column 1", "Column 2 (MyO)", "Column 3"));
         DefaultTableModel tableM = new DefaultTableModel(rowData, hdr);
        table3 = new JTable(tableM);
        TableColumn tc = table3.getColumnModel().getColumn(3);   
        tc.setCellEditor(table3.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(table3.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxColumnHeader(table3, new MyItemListener()));
        scp3 = new JScrollPane(table3);
         scp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
         this.add(scp3);
      //�berschrieben, so dass eine Beendigung beim Schlie�en des Fensters m�glich ist
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent; 
         protected int column; 
         protected boolean mousePressed = false; 
         protected JTable myTable;
         public CheckBoxColumnHeader(JTable t, ItemListener itemListener) {   
              rendererComponent = this;   
              rendererComponent.addItemListener(itemListener);
              myTable = t;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              JTableHeader header = null;
              if (table != null) {     
                   header = (JTableHeader)table.getTableHeader();     
                    if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());       
                        rendererComponent.setBackground(header.getBackground());       
                        rendererComponent.setFont(header.getFont());       
                        header.addMouseListener(rendererComponent); 
              setColumn(column);   
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));   
              return rendererComponent; 
         protected void setColumn(int column) {this.column = column; } 
         public int getColumn() {return column; }
         protected void handleClickEvent(MouseEvent e) {
              if (mousePressed) {
                   mousePressed=false;     
                   JTableHeader header = (JTableHeader)(e.getSource());
                   JTable tableView = header.getTable();
                   TableColumnModel columnModel = tableView.getColumnModel();
                   int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                   int column = tableView.convertColumnIndexToModel(viewColumn);
                   if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
                        doClick();
         public void mouseClicked(MouseEvent e) {   
              handleClickEvent(e);   
              ((JTableHeader)e.getSource()).repaint(); 
         public void mousePressed(MouseEvent e) {   
              mousePressed = true; 
         public void mouseReleased(MouseEvent e) {  }
         public void mouseEntered(MouseEvent e) {  }
         public void mouseExited(MouseEvent e) {  }
         public JTable getTable() {return myTable; }
    public class MyItemListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
             CheckBoxColumnHeader source = (CheckBoxColumnHeader)e.getSource();
             if (source instanceof AbstractButton == false) return;
             boolean checked = e.getStateChange() == ItemEvent.SELECTED;
             for (int x = 0, y = source.getTable().getRowCount(); x < y; x++) {
                  source.getTable().setValueAt(new Boolean(checked),x,3);     
    As originally said, the checkbox in the header column overlays the table borders and also has a different background shading than the other header columns.

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • How do I create a jtable with horizontalScroll bar,plz help me!

    I created a jtable component,Because my table's columns has 50 items,I must need a horizontalScroll Bar.
    but I find the horizontalScroll don't display,when I add record to the jtable,the verticalScroll Bar is showed.How do I create a jtable with horizontalScroll bar,can u help me!
    thank you in advance!

    Hi,
    This piece of code will help :
         //Get the Component Adapter for taking action against resizing of
    //of Panel
    ComponentListenerAdapter componentAdapter =
    new ComponentListenerAdapter()
    //Get the scrollbar or remove the scrollbar upon resizing
    protected void resizingAction()
    Container tableParent = table.getParent();
    if (tableParent instanceof JViewport)
    //Check if the width of the Table Parent Container
    //is less than the Preferred Size of the Table
    if (tableParent.getSize().getWidth() <
    table.getPreferredSize().getWidth())
    //Yes it is
    //Remove the Auton Resize Function and get the
    //Scrollbar
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    else
    //No it is not
    //Get the Auto Resize functionality back in place
    table.setAutoResizeMode(
    JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    //Add the component Adapter to the Table Header
    table.getTableHeader().addComponentListener(componentAdapter);
    private abstract class ComponentListenerAdapter
    implements ComponentListener
              * The <code>componentHidden<code> method has no implementation
              * @param event The Event occured whenever the Component is Hidden
              public void componentHidden(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentShown</code> method has no implementation
              * @param event The Event occured whenever the Component is Shown
              public void componentShown(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentMoved</code> method has no implementation
              * @param event The Event occured whenever the Component is Moved
              public void componentMoved(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentResized</code> method is invoked whenever the
              * component is resized. The resizing action will set the columns and
              * scrollbar to act properly
              * @param event The Event occured whenever the Component is Resized
              public void componentResized(ComponentEvent event)
                   resizingAction();
    * Subclasses of this override this method to determine what is to be
    * done once the Component has been Resized
    protected abstract void resizingAction();
    Hope this will solve all your JTable horizontal resizing problems
    --j                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Can we create JTable with multiple rows with varying number of columns ?

    Hi All,
    I came across a very typical problem related to JTable. My requirement is that cells should be added dynamically to the JTable. I create a JTable with initial size of 1,7 (row, columns) size. Once the 7 columns are filled with data, a new row should be created. But the requirement is, the new row i.e. second row should have only one cell in it initially. The number of cells should increase dynamically as the data is entered. The table is automatically taking the size of its previous row when new row is added. I tried by using setColumnCount() to change the number of columns to '1' for the second row but the same is getting applied to the first row also.
    So can you please help me out in this regard ? Is it possible to create a JTable of uneven size i.e. multiple rows with varying number of columns in each row ?
    Thanks in Advance.

    Well a JTable is always going to paint the same number of columns for each row. Anything is possible if you want to rewrite the JTable UI to do this, but I wouldn't recommend it. (I certainly don't know how to do it).
    A simpler solution might be to override the isCellEditable(...) method of JTable and prevent editing of column 2 until data in column 1 has been entered etc., etc. You may also want to provide a custom renderer that renderers the empty column differently, maybe with a grey color instead of a white color.

  • Print JTable with row headers

    I am using the fancy new printing capablities in java 1.5 to print my JTable and wow is it ever slick!
    PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
    set.add(OrientationRequested.LANDSCAPE);
    this.matrixJTable.print(JTable.PrintMode.NORMAL, null, null, true, set, false);Its just that easy. Way to go sun!
    The one problem that I am encountering is that my row headers don't print. The problem is that JTables don't support row headers, you have to use a JScrollPane for that.
    I need a way to print my JTable so that the row headers show up in the printout... and hopefully still use the warm and fuzzy new printing capabilities of JTable printing in java 1.5.
    (ps/ Isn't it time to add row header support to JTables?)

    The problem is that JTables don't support row headers, you have to use a JScrollPane for that.Well technically JTable's don't really support column headers either. It is a seperate component (JTableHeader). A JTable will automatically add its table header to the table header area of a JScrollPane. (but you don't have to use a jscrollpane to see the column headers, it is just the quickest and easiest way).
    Really shouldn't be hard to implement a row header and manually add it to the scroll panes row header area or use a BorderLayout and put your row header in the WEST and put your table in the CENTER if you don't want a scroll pane.
    Of course this won't help you with your printing issue.

  • Override the ToolTipText of the JTable with JButton ToolTipTex(pls see msg)

    Hi All,
    Could you please me to solve this problem?
    I have two Icons display on 2 JButtons (2 different ToolTipText for buttons). The Buttons are display on a JPanel. The Panel is display on one of the cell inside JTable. Is it possible that when I move the mouse over each Icon it will displays the ToolTipText of each of the JButton (I am try to replace the ToolTipText of the JTable with the ToolTipText of the JButton when mouse over and when I move the mouse to the next JButton I get a different ToolTipText). The reason I am using the JButton is that in the future I will add actionListener() to do something when the user click on it.
    I have try working with glassPane, addMouseMotionListener, MouseEvent.getPoint(), SwingUtilities.convertPoint, SwingUtilities.getDeepestComponentAt.
    Thank you in advance.
    Note: I am getting the Icons from Object [].

    Hello, the following is one ugly piece of code but I guess that's pretty much what you were after. Just test the tooltip and you'll see that it depends both on the cell and on which of the two buttons is hovered.import javax.swing.*;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    public class TestTooltipTable {
         private static class CustomTableCellRenderer implements TableCellRenderer {
              private JButton theLeftButton;
              private JButton theRightButton;
              private JPanel thePanel;
              public CustomTableCellRenderer() {
                   theLeftButton = new JButton("left action");
                   theRightButton = new JButton("right action");
                   thePanel = new JPanel(new GridLayout(1, 2)) {
                        public String getToolTipText(MouseEvent e) {
                             Point p = e.getPoint();
                             Rectangle leftRect = theLeftButton.getBounds();
                             Rectangle rightRect = theRightButton.getBounds();
                             if (leftRect.contains(p)) {
                                  return theLeftButton.getToolTipText();
                             } else if (rightRect.contains(p)) {
                                  return theRightButton.getToolTipText();
                             return " ";
                   thePanel.add(theLeftButton);
                   thePanel.add(theRightButton);
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                                        boolean hasFocus, int row, int column) {
                   String text = (String)value;
                   theLeftButton.setToolTipText("left action " + text);
                   theRightButton.setToolTipText("right action " + text);
                   return thePanel;
         public static void main(String[] args) {
              final JFrame frame = new JFrame(TestTooltipTable.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Object[][] data = {{"1", "A"}, {"2", "B"}, {"3", "C"}};
              String[] columnNames = {"Number", "Letter"};
              JTable table = new JTable(data, columnNames) {
                   public String getToolTipText(MouseEvent event) {
                        return super.getToolTipText(event);
              table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());
              ToolTipManager.sharedInstance().registerComponent(table);
              frame.getContentPane().add(new JScrollPane(table));
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }

  • Save JTable and JCheckBox content

    I've made a JTable(working with DefaultTableModel). One of the columns contains JCheckBoxes. I would like to save the data into a file, but i don't know how to manage this.
    Is there somebody who knows a possible solution?!
    Thx

    I have code which can save the jtable, but i doesn't work with jcheckboxes in the jtable
    CODE:
    public void saveTable()
    if (table.getRowCount() == 0)
    System.out.println("Empty list");
    return;
    try
    FileOutputStream fos = new FileOutputStream("data.dat");
    Writer out = new OutputStreamWriter(fos,"UTF8");
    for (int i = 0; i < table.getRowCount(); i++)
    for(int j=0; j < table.getColumnCount(); j++)
    String value = (String)table.getValueAt(i,j) + "|";
    out.write(value);
    out.close();
    catch(IOException e)
    System.out.println("Error IOException " + e.getMessage());
    }

Maybe you are looking for

  • Sales Order Material and its MOQ mass change

    *The issue is related to our Spare parts Ordering process in our company.* We have a concept of having 65 days of back orders. Hence there will be lot many open orders in the system. The Material code will be changed from (for eg) M01 to M02. Hence f

  • How can set the responsiblity name and operatingunit name at header level y

    Dear all Good Morning i have to set the respname and org name at header level i taken the item at page level userinfo it is coming the right side of the page i want to be set at header level only in left side top only... is there any item style for t

  • MySAP PLM

    In all the presentations that are present in service.sap.com related to mySAP PLM it talks about Quality Management using mySAP PLM, Life cycle data management and life cycle process management. Under Life cycle data management we have Document manag

  • Route schedule issue

    Hi I'm using route schedules and I have examples where the route schedules dictates that the GI data should be on tuesdays. If I have a requested delivery date fare in the future and the goods is avaliable I get the wrong delivery date. If I have req

  • Ipad 4 black screen won't boot itunes does recognize and tried to restore

    A friend of mine brought me an ipad that she was given. The owner didn't know what happened and just went and bought another one. Must be nice! Anyway, my friend wants to get this fixed and brought it to me because she is no kind of geek. I'm running