Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Trying to hide  columns while using Default table Model - JTable

Posted on 2001-06-07
Medium Priority
Last Modified: 2012-08-13
I have extended JTable as follows...

public class MyTable extends JTable
    public MyTable()
    public MyTable(java.lang.String resourceTag, javax.swing.table.TableModel tableModel)
        super(resourceTag, tableModel);

    public void createDefaultColumnsFromModel()
    {       super.createDefaultColumnsFromModel();
        TableColumnModel model = getColumnModel();

in my Dialog I am implementing...

protected MyTable m_tblSetMetric = null;

m_tblmdlSetMetric     =  new MDefaultTableModel("setMetricLis", dataOut);
m_tblSetMetric           =   new MyTable("setMetricLis", m_tblmdlSetMetric);
MTablePane tp           =   new MTablePane(12, true, null, (MTable)m_tblSetMetric, m_tblmdlSetMetric);

I am not getting any exception but the dialog doesn't show me the column names that I am trying to pull from properties file. If I comment out


line then it shows all the columns...Am I missing somethign or doing wrong...
Appreciate any help...

Question by:manishkp
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2

Expert Comment

ID: 6167213
Is coming ...

Accepted Solution

Ovi earned 400 total points
ID: 6167437
This example works on the user defined number of rows/columns. To modify the numbers, modify the line   SmartTable table = new SmartTable(60, 10); To load your custom columns names set the appropiate number in the above line and modify the method : SmartTableModel.createHeaders() to make a trivial read from properties files.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TableColumnCustomizer extends JFrame  {
      JPanel actions = new JPanel();
  JSplitPane spliter = new JSplitPane();
  JLabel status = new JLabel("Status :");
  SmartTable table = new SmartTable(60, 10);
  TableColumnModel colModel = table.getColumnModel();
      public TableColumnCustomizer()  {
  private void init() {
        setLocation(150, 100);
    setSize(800, 600);
    getContentPane().setLayout(new BorderLayout());
    // init actions
    spliter.setLeftComponent(new JScrollPane(actions));
    spliter.setRightComponent(new JScrollPane(table));
    getContentPane().add(spliter, BorderLayout.CENTER);
    getContentPane().add(status, BorderLayout.SOUTH);
  private void initActions()  {
        int c = table.getColumnCount();
    actions.setLayout(new GridLayout(c, 1));
    for(int i=0; i<c; i++) {
          JCheckBox cb = new JCheckBox("Hide/Show column " + (i));
      cb.addActionListener(new ActionAdapter(i));
  class ActionAdapter implements ActionListener {
        int pos;
        TableColumn column;
        public ActionAdapter(int col)  {
              pos = col;
      column = colModel.getColumn(pos);
        public void actionPerformed(ActionEvent ae) {
              JCheckBox tmp = (JCheckBox) ae.getSource();
              String lbl = tmp.getLabel();
              boolean selected = tmp.isSelected();
              status.setText(lbl + " : " + selected);
              int idx = Integer.parseInt(lbl.substring(lbl.length() - 2).trim());
              if(!selected) {
        colModel.moveColumn(table.getColumnCount() - 1, pos);
              } else {

      class SmartTable extends JTable {
        SmartTableModel model;
            public SmartTable(int rows, int cols) {
                  model = new SmartTableModel(rows, cols);
                  setBackground(new Color(255, 239, 185));
            protected void createColumns() {
                  for(int i = 0; i<model.getColumnCount(); i++) {
                        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
            public void setSelectedRow(int row) {
                  if(row == -1)
                  else {
                        setRowSelectionInterval(row, row);
            public void setSelectedCol(int col) {
                  if(col == -1)
                  else {
                        setColumnSelectionInterval(col, col);
      class SmartTableModel extends AbstractTableModel {
        int rows = 10;
    int columns = 10;
            protected ColumnDescriptor[] cols;
            protected Vector dObjects;

            public SmartTableModel(int maxRows, int maxCols) {
                  dObjects = new Vector();
      rows = maxRows;
      columns = maxCols;
                  addTableModelListener(new ModelAdapter());
    private void createHeaders() {
          cols = new ColumnDescriptor[columns];
          for(int i=0; i<columns; i++) {
            ColumnDescriptor c = new ColumnDescriptor("Field" + String.valueOf((i)), 40,
        cols[i] = c;

            public void addData() {
                  Vector data = new Vector();
                  for(int i=0; i<rows; i++) {
                        SmartData[] sd = new SmartData[columns];
                        for(int j=0; j<columns; j++) {
                          String d = "Cell [" + i + ", " + j + "]";
                      sd[j] = new SmartData(d);
                  for(int i = 0; i<data.size(); i++) {
                        dObjects.addElement((SmartData[]) data.elementAt(i));
    public SmartData getSmartData(int row, int col) {

            protected void updateObjects() {

            public int getColumnCount() {

            public int getRowCount() {

            public String getColumnName(int c) {

            public boolean isCellEditable(int row, int col) {

            public Object getValueAt(int row, int col) {
                  if(getRowCount() <= 0)
                        return "";
                        return "";
                  SmartData[] sd = (SmartData[]) dObjects.elementAt(row);
            class ModelAdapter implements TableModelListener  {
                  public void tableChanged(TableModelEvent tme) {

      class ColumnDescriptor {
        public String name;
        public int width;
        public int alignment;
        public ColumnDescriptor(String n, int w, int a) {
          name = n;
          width = w;
          alignment = a;
  class SmartData {
        String data;
        public SmartData(String d) {
          data = d;
      public static void main(String[] args) {
            (new TableColumnCustomizer()).setVisible(true);

Expert Comment

ID: 8289458
Force Accepted

Community Support Moderator @Experts Exchange

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question