import com.sun.java.swing.JTable; import com.sun.java.swing.table.AbstractTableModel; import com.sun.java.swing.JScrollPane; import com.sun.java.swing.JPanel; import com.sun.java.swing.JFrame; import java.awt.GridLayout; import java.awt.Dimension; import java.awt.event.WindowListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class SimpleTableDemo extends JPanel { public SimpleTableDemo() { JTable table = new JTable(new MyTableModel()); //Create the scroll pane and add the table to it. JScrollPane scrollPane = JTable.createScrollPaneForTable(table); scrollPane.setPreferredSize(new Dimension(400, 100)); //Add the scroll pane to this panel. setLayout(new GridLayout(1, 0)); add(scrollPane); } /* * Instead of creating this class, you COULD just put columnNames * and data into the SimpleTableDemo class, creating the table * with new JTable(data, columnNames). However, if you tried to * add any functionality to the table, such as editing, then you'd * run into trouble. * * It's best in the long run to create your own table model. * (Besides, it's not difficult at all!) */ class MyTableModel extends AbstractTableModel { final String[] columnNames = {"First Name", "Last Name", "Sport", "Est. Years Experience"}; final String[][] data = { {"Mary", "Campione", "Snowboarding", "5"}, {"Alison", "Huml", "Rowing", "3"}, {"Kathy", "Walrath", "Chasing toddlers", "2"}, {"Mark", "Andrews", "Speed reading", "20"}, {"Angela", "Lih", "Teaching high school", "4"} }; public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } } public static void main(String[] args) { JFrame frame = new JFrame("SimpleTableDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add("Center", new SimpleTableDemo()); frame.setSize(400, 125); frame.setVisible(true); } }