import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;

import javax.swing.*;
import javax.swing.table.*;

public class ThreadTableModel extends AbstractTableModel {

  public ThreadTableModel(Thread[] threads) {
    this.threads=threads;
  }

  public int getColumnCount() {
    return 3;
  }

  public int getRowCount() {
    return threads.length;
  }
  
  public String getColumnName(int column) {
    return columnNames[column];
  }

  public Object getValueAt(int row, int column) {
    Thread thread=threads[row];
    switch(column) {
      case 0:
        return thread.getName();
      case 1:
        return new Integer(thread.getPriority());
      case 2:
        return Boolean.valueOf(thread.isDaemon());
    }
    throw new IllegalArgumentException("invalid column ("+row+','+column+')');
  }
  
  private static JCheckBox createCheckBox(final TableColumnModel columnModel,final int modelIndex) {
    final JCheckBox checkBox=new JCheckBox(columnNames[modelIndex]);
    checkBox.setSelected(true);
    
    final TableColumn column=columnModel.getColumn(modelIndex);
    
    checkBox.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (checkBox.isSelected())
          columnModel.addColumn(column);
        else
          columnModel.removeColumn(column);
      }
    });
    return checkBox;
  }
  
  public static JPanel createCheckBoxPanel(TableColumnModel columnModel) {
    JPanel panel=new JPanel(null);
    panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
    for(int i=0;i<columnModel.getColumnCount();i++)
      panel.add(createCheckBox(columnModel,i));
    return panel;
  }
  
  private final Thread[] threads;
  private final static String[] columnNames={
    "Name","Priority","Daemon"
  };
  
  public static void main(String[] args) {
    ThreadGroup root=Thread.currentThread().getThreadGroup().getParent();
    Thread[] threads=new Thread[root.activeCount()];
    int nThreads=root.enumerate(threads);
    threads=(Thread[])Arrays.asList(threads).toArray(new Thread[nThreads]);
    ThreadTableModel model=new ThreadTableModel(threads);
    
    JTable table=new JTable(model);
    
    JPanel panel=new JPanel(new BorderLayout());
    panel.add(new JScrollPane(table),BorderLayout.CENTER);
    panel.add(createCheckBoxPanel(table.getColumnModel()),
      BorderLayout.WEST);
    
    JFrame frame=new JFrame("ThreadTableModel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(panel);
    frame.setSize(400,300);
    frame.show();
  }
}