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.

Similar Messages

  • 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/

  • Keyboard Access For a Column in JTable with default editor as JComboBox

    I want to get Key board access for a column in JTable.
    The user should be able to select from a drop down list for the column with default
    editor set as JComboBox.
    Presently,it works fine with mouse,also I am able to focus it with Keyboard using
    ALT+Up keys,but how to make drop down list appear.
    Plz help,it's urgent.
    Thanks in Advance

    Hi,
    In addition to setting DO_SUM = 'X' you need to specify function in H_FTYPE field. It should be set to 'AVG' in your case.
    ls_fielcat-do_sum = 'X'.
    ls_fieldcat-h_ftype = 'AVG.

  • Horizontal scrolling in a JTable with fixed-size columns

    Hello,
    I have come to a roadblock concerning the following issue. Perhaps someone can share their ideas...
    I have a JTable with three fixed-size columns. I implemented a JScrollPane with vertical and horizontal scrolling. However, the text inserted into the last column is too long to fit in the specified column width. I would like to be able to scroll the table so that I can view all of the text in the last column. Right now, the text cuts off and ends with three dots (...). Is there a way in which a horizontal scroll bar can be implemented to view all the text in the last column?
    Here is a portion of my code:
    num_of_rows_Table2 = (int) Math.pow(3, num_of_vars);
    String[] colunmNames_Table2 = {"Decimal Identifier", "Ternary Identifier", "Cancellation of nonimplicants"};
    dataModel2 = new DefaultTableModel(colunmNames_Table2, num_of_rows_Table2);
    SpaceOfTermsTable = new JTable(dataModel2);
    for (int z = 0; z < num_of_rows_Table2; z++)
    SpaceOfTermsTable.setRowHeight(z, row_height);
    SpaceOfTermsTable.setBounds(new Rectangle(x1_Table2, y1_Table2, width_of_pane2, height_pane2));
    SpaceOfTermsTable.getTableHeader().setReorderingAllowed(false);
    for (int i = 0; i < 2; i++)
    TableColumn col = SpaceOfTermsTable.getColumnModel().getColumn(i);
    col.setMinWidth(colwidth_Table2);
    col.setMaxWidth(colwidth_Table2);
    col.setPreferredWidth(colwidth_Table2);
    TableColumn lastcol = SpaceOfTermsTable.getColumnModel().getColumn(2); lastcol.setMinWidth(lastcol_Table2);
    lastcol.setMaxWidth(lastcol_Table2);
    lastcol.setPreferredWidth(lastcol_Table2);
    SpaceOfTermsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    scrollPanel2 = new JScrollPane(SpaceOfTermsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPanel2.setAutoscrolls(true);
    scrollPanel2.setBounds(new Rectangle(x1_Table2, y1_Table2, width_of_pane2, height_pane2));
    Thanks in advance for all of the help!

    Hi, I hava a similar problem than yours - can you tell me how you sorted out yer's?

  • Sum of two columns of Jtable in Jclient (summarized columns)

    I want to display the sum of two columns of Jtable in a text box, just as we use to do in Forms developer.
    How is this possible in Jclient.
    I would be glad if someone can give a detail info about it.

    Actually I wanted to sum the values of a column when a user enters a value in the Jtable when a new record is created. before it is commited
    That summarized value which I want in the textbox will then be used in the validation rule.

  • 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

  • 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.

  • Creating a JTable with resizeable columns and Horizontal Scrollbar

    Hi,
    I would like to create a JTable with about 24 columns in it. The problem is, my ViewPort in my JScrollPane is about 3-400pixels wide, and the JTable tries to cram itself into the ViewPort. This makes the columns too tiny to read. I'd like it to do something a little more sensible, like use the PreferredSize of the columns. Can anyone point me in the right direction to keep JTable from creating scrunched up little columns, so that it creates columns that are at least partially readable? Thanks.
    BTW, I suppose I could set NO_AUTO_RESIZE but I would rather not do that. I like being able to resize columns. Basically what I want to do is control the JTable's width and not worry about the ViewPort's width.

    This made it impossible to resize columns. Works fine for me:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableHorizontal extends JFrame
        public TableHorizontal()
            JTable table = new JTable(5, 10);
            table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            table.getColumnModel().getColumn(0).setPreferredWidth(10);
            table.getColumnModel().getColumn(1).setPreferredWidth(20);
            table.getColumnModel().getColumn(2).setPreferredWidth(30);
            table.getColumnModel().getColumn(3).setPreferredWidth(40);
            table.getColumnModel().getColumn(4).setPreferredWidth(50);
        public static void main(String[] args)
            TableHorizontal frame = new TableHorizontal();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Double click on a JTable row.

    I got and run a sample about double click on a JTable and it works fine. This sample defines a TableModel as shown at the end this note.
    On the other hand, I have an application in which I have defined a JTable
    using the DefaultTableModel as follows :
    DefaultTableModel dtm = new DefaultTableModel(data, names);
    JTable table  = new JTable(dtm);  where data and names are String arrays.
    Of course the mouse listener stuffs have been also specified.
    table.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e){
          if (e.getClickCount() == 2){
             System.out.println(" double click" );
         } );Because the difference with the sample was the table model,
    I changed it with the DefaultTableModel class. At this point, the Double click does not work anymore.
    So I gues it should be an option which prevents double click to work.
    I thought of using mousePress() instead of mouseClick(), but it's very dangerous (I tried). . If by error the user clicks twice (instead of only once) the mousePress method is invoked twice for the same entry
    My question is now simple, may I use double click on a JTable with the default table model. If so, what I have to do ?
    Thanks a lot
    Gege
    TableModel dataModel = new AbstractTableModel() {
         public int getColumnCount() { return names.length; }
         public int getRowCount() { return data.length;}
         public Object getValueAt(int row, int col) {return data[row][col];}
         public String getColumnName(int column) {return names[column];}
         public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
         public void setValueAt(Object aValue, int row, int column) {
           data[row][column] = aValue;
         };

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ClickIt extends MouseAdapter
        public void mousePressed(MouseEvent e)
            JTable table = (JTable)e.getSource();
            Point p = e.getPoint();
            if(e.getClickCount() == 2)
                System.out.println("table.isEditing = " + table.isEditing());
            int row = table.rowAtPoint(p);
            int col = table.columnAtPoint(p);
            String value = (String)table.getValueAt(row,col);
            System.out.println(value);
        private JTable getLeftTable()
            final String[] names = { "column 1", "column 2", "column 3", "column 4" };
            final Object[][] data = getData("left");
            TableModel dataModel = new AbstractTableModel() {
                public int getColumnCount() { return names.length; }
                public int getRowCount() { return data.length;}
                public Object getValueAt(int row, int col) {return data[row][col];}
                public String getColumnName(int column) {return names[column];}
                public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
                public void setValueAt(Object aValue, int row, int column) {
                    data[row][column] = aValue;
            JTable table = new JTable(dataModel);
            return configure(table);
        private JTable getRightTable()
            String[] colNames = { "column 1", "column 2", "column 3", "column 4" };
            JTable table = new JTable(new DefaultTableModel(getData("right"), colNames));
            return configure(table);
        private Object[][] getData(String s)
            int rows = 4, cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                for(int col = 0; col < cols; col++)
                    data[row][col] = s + " " + (row*cols + col + 1);
            return data;
        private JTable configure(JTable table)
            table.setColumnSelectionAllowed(true);
            table.setCellSelectionEnabled(true);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.addMouseListener(this);
            return table;
        private JPanel getContent()
            JPanel panel = new JPanel(new GridLayout(1,0,0,5));
            panel.add(new JScrollPane(getLeftTable()));
            panel.add(new JScrollPane(getRightTable()));
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new ClickIt().getContent());
            f.pack();
            f.setVisible(true);
    }

  • Oracle 8i DATE column returned wrong with 9i thin driver

    I have an Oracle 8i database with a column named "timestamp" with the following column metadata:
    DATA_TYPE=93
    TYPE_NAME=DATE
    I execute the following statement:
    select "timestamp" from oracle_data_log
    When I look at the result set metadata using the Oracle 9i drivers, I get (as expected):
    getColumnType=93
    getColumnTypeName=DATE
    getColumnClassName=java.sql.Timestamp
    When I look at the result set metadata using the Oracle 9i drivers, I get:
    getColumnType=91
    getColumnTypeName=DATE
    getColumnClassName=java.sql.Timestamp
    That column type 91 indicates it is SQL type DATE which is for date only values (no time information).
    Our code (working against many different databases with many different drivers) works off the column type metadata and messes up. (Obviously I can look at the column class name string as well / instead, but I'd like the column type to come back with the proper SQL type.)
    As I said, it works as expected with the 8i thin driver (and the DataDirect JDBC driver).

    Thanks for the info.
    It seems to me that returning a SQL type DATE (which means it only stores date information) for an Oracle DATE type (which stores date and time information) is the wrong thing to do. The Oracle DATE type stores date and time information which corresponds to the SQL TIMESTAMP type. It should return TIMESTAMP as the SQL type.
    It seems like it would confuse a client application into thinking there is no time information available, which there is.
    A friend suggested that since a SELECT on a DATE value only displays the date portion and not the time portion, that might be why they did it, but that still doesn't sound right. The Oracle DATE type stores date and time which corresponds to the SQL TIMESTAMP type.
    I guess they might have done it to distinguish between Oracle DATE and TIMESTAMP types, but I still don't like it...
    I wonder if there is any documentation on why Oracle made the decision?

  • 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.

  • Cannot auto size columns in iTunes 10.4.  Columns are all mixed up with headings I have never seen. Cannot change by right clicking on columns.

    Cannot auto size columns in iTunes 10.4.  Columns are all mixed up with headings I have never seen. Cannot change by right clicking on columns. Cannot order albums alphabetically by double clicking on heading.

    Very many thanks to you, Putaro!  Your answer provided the solution. It was a buggy plug-in that turned out to be the culprit.
    You're off the hook, Apple, and my apologies for stating that you let a dog run loose. You skated by this time, Apple. But I'm watching you.
    But again, Putaro's reference to the plugins I had installed over the years turned out to illuminate the problem. I have several plugins in my iTunes plugins folder, pretty much all designed to add more visualizer functionality. I removed all of them, and ALL of the problems I noted in my post went away, with full iTunes functionality restored.
    I began adding the plugins back to hopefully single out the culprit. Among the ones I had been using included fielder, G-Force, Timestrech, volcanokit, QuartzComposer, and Jax. I hadn't used any of them in a while - probably at least a verison or more back in iTunes updates, but iTunes continued to work with all of them installed. Currently, only QuartzComposer continues to work in iTunes 10.4. The rest no longer even show up as visualizer opitons, with one exception. Jax does show up, but does not work. AND THE PRESENCE OF JAX IS WHAT KILLED MY ITUNES.
    I looked into it and went back to the developer, and it appears that they discontinued developing Jax some time ago - evidently, it was buggy and crash prone. I remember after buying it, having problems with it - having never worked to its touted potential, but I didn't pursue it, and never uninstalled it. Leaving it in there caused all iTunes functionality to cease with the iTunes 10.4 update.
    If you've got Jax installed, consider removing it before updating to iTunes 10.4.
    My iTunes is now working right as rain, thanks again to Putaro!
    -Jon

  • 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 :)

  • 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.

Maybe you are looking for

  • Sending SMS via Bluetooth not working

    Hi, I have two Nokia phones, an N73 and an older 6600. I was able to pair both with the Bluetooth in my MacBook Pro SR. I can access the web via dial-up networking, so that's working fine. However, I am unable to send SMS via AddressBook over the pho

  • Wildcards in Classpath for JNI-Calls

    Is it possible to use wildcards in the classpath for KNI-Calls? I would like to use wildcard for jni-calls like for normal java-calls (java -classpath *.jar ...), but it is not working. JDK version is JDK 1.5.0 on Win32

  • InDesign Mac Trial Won't Open

    Hi, I was attempting a Mac trial of InDesign, but it won't open without crashing. I deleted and re-downloaded and installed, but it still won't open. Just crashes after attempting to open. Can you help me?

  • Since downloading newest itunes I can't transfer podcasts from desktop to ipod. ***??

    I got the newest itunes version and since then when I download a podcast to my desktop I can't transfer it to my ipod. I used to drag it over with no problem. Now I just get the circle with a line. Can't open on itunes, can't put it in music library.

  • Can we call an SAP transaction in Webdynpro

    Hi, I have a requirement to call an SAP transaction in Webdynpro, ie on clicking a button in a view, the particular SAP transaction has to come . Kindly tell me how to do it. Regards, Lakshmi