import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import java.awt.Dimension;

import java.awt.GridLayout;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

public class SimpleTableDemo extends JPanel {

private boolean DEBUG = false;

public SimpleTableDemo() {

super(new GridLayout(1,0));

String[] columnNames = {"姓",

"名",

"运动",

"年龄",

"性别"};

Object[][] data = {

{"王", "兵",

"滑雪", new Integer(15), "男"},

{"李", "红红",

"划船", new Integer(16), "女"},

{"田", "小丽",

"体操", new Integer(14), "女"},

{"孙", "刚强",

"长跑", new Integer(18), "男"},

{"雷", "文涛",

"武术", new Integer(15), "男"}

};

final JTable table = new JTable(data, columnNames);

table.setPreferredScrollableViewportSize(new Dimension(500, 70));

if (DEBUG) {

table.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

printDebugData(table);

}

});

}

//创建滚条窗格，并把表格加到里面

JScrollPane scrollPane = new JScrollPane(table);

//把这个滚条窗格教导这个面板上

add(scrollPane);

}

private void printDebugData(JTable table) {

int numRows = table.getRowCount();

int numCols = table.getColumnCount();

javax.swing.table.TableModel model = table.getModel();

System.out.println("数据的值: ");

for (int i=0; i < numRows; i++) {

System.out.print(" 行 " + i + ":");

for (int j=0; j < numCols; j++) {

System.out.print(" " + model.getValueAt(i, j));

}

System.out.println();

}

System.out.println("--------------------------");

}

/**

* 创建并显示这个 GUI，由事件分配线程来处理。

*/

private static void createAndShowGUI() {

//创建并设置窗口

JFrame frame = new JFrame("SimpleTableDemo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//创建 content 窗格

SimpleTableDemo newContentPane = new SimpleTableDemo();

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

//显示这个窗口

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

//给事件分配线程一个作业：创建并显示这个 GUI

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}