Solved

Trying to hide  columns while using Default table Model - JTable

Posted on 2001-06-07
3
292 Views
Last Modified: 2012-08-13
I have extended JTable as follows...

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

    public void createDefaultColumnsFromModel()
    {       super.createDefaultColumnsFromModel();
        TableColumnModel model = getColumnModel();
columnModel.getColumn(3);
            this.removeColumn(column);
        }
        model.removeColumn(model.getColumn(3));
       
    }
}

in my Dialog I am implementing...

protected MyTable m_tblSetMetric = null;

m_tblmdlSetMetric     =  new MDefaultTableModel("setMetricLis", dataOut);
m_tblSetMetric           =   new MyTable("setMetricLis", m_tblmdlSetMetric);
m_tblSetMetric.createDefaultColumnsFromModel();
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

model.removeColumn(model.getColumn(3));


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

0
Comment
Question by:manishkp
  • 2
3 Comments
 
LVL 9

Expert Comment

by:Ovi
ID: 6167213
Is coming ...
0
 
LVL 9

Accepted Solution

by:
Ovi earned 100 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()  {
            super();
    init();
      }
 
  private void init() {
        setLocation(150, 100);
    setSize(800, 600);
    getContentPane().setLayout(new BorderLayout());
    // init actions
    initActions();
    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));
          actions.add(cb);
    }
  }
 
  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.addColumn(column);
        colModel.moveColumn(table.getColumnCount() - 1, pos);
              } else {
                    colModel.removeColumn(column);
              }
      table.sizeColumnsToFit(-1);
        }
  }

      class SmartTable extends JTable {
        SmartTableModel model;
   
            public SmartTable(int rows, int cols) {
                  model = new SmartTableModel(rows, cols);
                  createColumns();
                  setModel(model);
                  setForeground(Color.red);
                  setBackground(new Color(255, 239, 185));
                  setGridColor(Color.orange);
                  setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                  setSelectedRow(0);
                  setSelectedCol(0);
            }
            
            protected void createColumns() {
                  for(int i = 0; i<model.getColumnCount(); i++) {
                        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                        renderer.setHorizontalAlignment(model.cols[i].alignment);
                        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
                        addColumn(column);
                  }
            }
   
            public void setSelectedRow(int row) {
                  if(row == -1)
                        return;
                  else {
                        setRowSelectionInterval(row, row);
                  }
            }
            
            public void setSelectedCol(int col) {
                  if(col == -1)
                        return;
                  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;
      createHeaders();
      addData();
                  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,
        JLabel.LEFT);
        cols[i] = c;
          }
    }


            public void addData() {
                  dObjects.removeAllElements();
                  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);
                        }
                    data.addElement(sd);
                  }
                  for(int i = 0; i<data.size(); i++) {
                        dObjects.addElement((SmartData[]) data.elementAt(i));
                  }
                  updateObjects();
            }
   
    public SmartData getSmartData(int row, int col) {
          return(((SmartData[])dObjects.elementAt(row))[col]);
    }

            protected void updateObjects() {
                  fireTableDataChanged();
            }

            public int getColumnCount() {
                  return(cols.length);
            }

            public int getRowCount() {
                  return(dObjects.size());
            }

            public String getColumnName(int c) {
                  return(cols[c].name);
            }

            public boolean isCellEditable(int row, int col) {
      return(false);
            }

            public Object getValueAt(int row, int col) {
                  if(getRowCount() <= 0)
                        return "";
                  if(row<0||row>=getRowCount())
                        return "";
                  SmartData[] sd = (SmartData[]) dObjects.elementAt(row);
      return(sd[col].data);
            }
            //*******************************************************************
            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);
      }
}
0
 

Expert Comment

by:SpideyMod
ID: 8289458
Force Accepted

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse compiler vs Installed JREs option 3 77
Weekend adv creator 3 14
Spring Framework HTTPSession management 1 24
xampp tool 12 31
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

863 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

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now