0

I have created a jTable class which is used with another class. Here the code:

public class Data_Table extends JFrame{
    DefaultTableModel dtm;
    JTable table;
    JScrollPane scrollPane;
    JFrame ventana;
    JButton button1,button2;
    JPanel pCentral,pSouth,pWindow;

    public void init() {
        String[] columnNames = {"CBD","abstract","final","native","private","protected","public",
                                "static","strictfp","synchronized","transient","volatile"};
        dtm = new DefaultTableModel(columnNames,0);     
        table = new JTable(dtm);
        scrollPane = new JScrollPane(table);

        button1 = new JButton("Ok");
        button2 = new JButton("Cancel");
    }

    public void addData(Object[] data) {
        dtm.addRow(data);
    }

    public void createWindow() {
        pCentral=new JPanel();
        pCentral.add(scrollPane);

        pSouth=new JPanel();
        pSouth.add(button1);
        pSouth.add(button2);

        pWindow=new JPanel(new BorderLayout());

        pWindow.add(pCentral,BorderLayout.CENTER);
        pWindow.add(pSouth,BorderLayout.SOUTH);

        ventana=new JFrame("");
        ventana.setContentPane(pWindow);

        ventana.add(scrollPane);
        ventana.setSize(1000,200);
        ventana.setLocationRelativeTo(null);
        ventana.setVisible(true);
    }
}

I want to transform the columns from abstract to volatile into jCheckBox. The result right now is this: enter image description here

How can I transform my table???

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
Jose
  • 49
  • 2

1 Answers1

2

Make use of the table models, specifically by creating a class that extends javax.swing.table.AbstractTableModel and overriding the getColumnClass() method and specifying that the method return Boolean.class for those specific columns.

A good place to start you off would be http://docs.oracle.com/javase/tutorial/uiswing/components/table.html specifically the link on Creating a Table Model

An example implementation could be:

    public class MyTableModel extends AbstractTableModel {
        /* Implement the various abstract methods and override any 
         * other methods you need to
         */

        public Class<?> getColumnClass ( int columnIndex ) {
            if ( (columnIndex == 1) || (columnIndex == 11 ) ) {
                return Boolean.class;
            }
        }
    }

After that, you would then apply the table model to your table using JTable's method, setModel()

fredmanglis
  • 487
  • 1
  • 5
  • 10
  • 1
    +1, Overriding the getColumnClass() method is the key to the answer. There is no need to create a new model from scratch. You can just extend DefaultTableModel to to this. – camickr Feb 26 '13 at 17:08