JTable是重中之重
1、通过数组构造一个简单的表格
public class table {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(300,200));
Object[][] cells = {
{"1","sdjf","23"},
{"2","jdf","22"}
};
Object[] columns = {"编号","姓名","年龄"};
JTable table = new JTable(cells,columns);
scrollPane.setViewportView(table);
panel.add(scrollPane);
f.getContentPane().add(panel);
f.setVisible(true);
}
}
2、通过模型构造表格,这是最重要的构造方法。
public class table {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(300,200));
JTable table = new JTable(new MyTableModel());
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
panel.add(scrollPane);
f.getContentPane().add(panel);
f.setVisible(true);
}
}
//构造自己的表格模型
class MyTableModel extends AbstractTableModel{
@Override
public int getColumnCount() {
return 3;
}
@Override
public int getRowCount() {
return 20;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rowIndex+","+columnIndex;
}
}