import javax.swing.table.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; /**Author Sonal Goyal, sonal_goyal@hotmail.com */ public class TableColumnTest implements ActionListener{ protected JFrame frame; protected JScrollPane scrollpane; protected MyTable table; public TableColumnTest() { //(1) Create the Table Model DefaultTableModel dm = new DefaultTableModel(); // Names for each of the columns String[] columnNames = { "This is going to be a really really long column header", "Column B", "Column C", "Column D", "Column E", "Column F", "Column G", "Column H", "Column I", "Column J" }; // the actual data values Integer[][] data = new Integer[8][10]; //populate the data matrix for (int row = 0; row < 8; row++){ for (int col = 0; col < 10; ++col){ data[row][col] = new Integer(1000000); } } //configure the model with the data and column headers dm.setDataVector(data, columnNames); //(2) Create the Table table = new MyTable(); //(3) Connect the model to the table table.setModel(dm); //(4) Create a scroll pane for the table scrollpane = new JScrollPane(table); //(5) Create a frame frame = new JFrame(); //(6) Create the buttons JButton resizeButton = new JButton("Resize Third Column"); JButton setResizeButton = new JButton("Set Second Column Not-Resizable"); JButton selectButton = new JButton("Select Fourth Column"); JButton headerButton = new JButton("Resize First Column Header"); //(7) Add action listeners to the buttons resizeButton.addActionListener(this); setResizeButton.addActionListener(this); selectButton.addActionListener(this); headerButton.addActionListener(this); //(8) Add all components to the frame and display frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); frame.getContentPane().add(scrollpane); frame.getContentPane().add(resizeButton); frame.getContentPane().add(setResizeButton); frame.getContentPane().add(selectButton); frame.getContentPane().add(headerButton); frame.setSize(300, 350); frame.setVisible(true); } //create the action listener public void actionPerformed(ActionEvent e){ //check which button was clicked if (e.getActionCommand().equals("Resize Third Column")){ System.out.println("Resize called - will resize third column to 300"); table.setColumnWidth(2, 300); } else if (e.getActionCommand().equals("Set Second Column Not-Resizable")){ System.out.println("Resizable called - second col will not be resizble now"); table.setResizable(1, false); } else if (e.getActionCommand().equals("Select Fourth Column")){ System.out.println("Select called - selecting fourth col "); table.setSelect(3, true); } else if (e.getActionCommand().equals("Resize First Column Header")){ System.out.println("Header called - the first column resized based on the header"); table.setHeaderSize(0); } //force gui udpate table.invalidate(); frame.invalidate(); frame.validate(); frame.repaint(); } public static void main(String[] args){ TableColumnTest test = new TableColumnTest(); } }