表格(Table)的使用与介绍
8-1:使用JTable组件:
类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.JTabel
在使用JTable以前,我们先看一下它的构造函数有哪些, 以及应该如何使用:
JTabel构造函数:
JTable():建立一个新的JTables,并使用系统默认的Model.
JTable(int numRows,int numColumns):建立一个具有numRows行,numColumns列的空表格,使用的是DefaultTableModel.
JTable(Object[][] rowData,Object[][] columnNames):建立一个显示二维数组数据的表格,且可以显示列的名称。
JTable(TableModel dm):建立一个JTable,有默认的字段模式以及选择模式,并设置数据模式。
JTable(TableModel dm,TableColumnModel cm):建立一个JTable,设置数据模式与字段模式,并有默认的选择模式。
JTable(TableModel dm,TableColumnModel cm,ListSelectionModel sm):建立一个JTable,设置数据模式、字段模式、与选择模式。
JTable(Vector rowData,Vector columnNames):建立一个以Vector为输入来源的数据表格,可显示行的名称。
我们先以Array构造方式,说明如何利用JTable来建立一个简单的表格:
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import java.util.*;
5 public class SimpleTable{
6 public SimpleTable(){
7 JFrame f=new JFrame();
8 Object[][] playerInfo={
9 {"阿呆",new Integer(66),new Integer(32),new Integer(98),new Boolean(false)},
10 {"阿呆",new Integer(82),new Integer(69),new Integer(128),new Boolean(true)},
11 };
12 String[] Names={"姓名","语文","数学","总分","及格"};
13 JTable table=new JTable(playerInfo,Names);
14 table.setPreferredScrollableViewportSize(new Dimension(550,30));
15 JScrollPane scrollPane=new JScrollPane(table);
16 f.getContentPane().add(scrollPane,BorderLayout.CENTER);
17 f.setTitle("Simple Table");
18 f.pack();
19 f.show();
20 f.addWindowListener(new WindowAdapter() {
21 public void windowClosing(WindowEvent e) {
22 System.exit(0);
23 }
24 });
24 }
25 public static void main(String[] args){
26 SimpleTable b=new SimpleTable();
27 }
28 }
JTable table=new JTable(p,n);
table.setPreferredScrollableViewportSize(new Dimension(550,30));
f.getContentPane().add(table.getTableHeader(),BorderLayout.NORTH);
f.getContentPane().add(table,BorderLayout.CENTER);
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SimpleTable2{
public SimpleTable2(){
JFrame f=new JFrame();
Object[][] p={
{"阿呆",new Integer(66),new Integer(32),new Integer(98),new Boolean(false),new Boolean(false)},
{"阿呆",new Integer(82),new Integer(69),new Integer(128),new Boolean(true),new Boolean(false)},
};
String[] n={"姓名","语文","数学","总分","及格","作弊"};
TableColumn column=null;
JTable table=new JTable(p,n);
table.setPreferredScrollableViewportSize(new Dimension(550,30));
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
for (int i=0;i<6;i++){
//利用JTable中的getColumnModel()方法取得TableColumnModel对象;再利用TableColumnModel界面所定义的getColumn()方法取
//TableColumn对象,利用此对象的setPreferredWidth()方法就可以控制字段的宽度.
column=table.getColumnModel().getColumn(i);
if ((i%2)==0)
column.setPreferredWidth(150);
else
column.setPreferredWidth(50);
}
JScrollPane scrollPane=new JScrollPane(table);
f.getContentPane().add(scrollPane,BorderLayout.CENTER);
f.setTitle("Simple Table");
f.pack();
f.show();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args){
new SimpleTable2();
}
}
import javax.swing.table.AbstractTableModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TableModel1{
public TableModel1() {
JFrame f = new JFrame();
MyTable mt=new MyTable();
JTable t=new JTable(mt);
t.setPreferredScrollableViewportSize(new Dimension(550, 30));
JScrollPane s = new JScrollPane(t);
f.getContentPane().add(s, BorderLayout.CENTER);
f.setTitle("JTable1");
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String args[]) {
new TableModel1();
}
}
class MyTable extends AbstractTableModel{
Object[][] p = {
{"阿呆", new Integer(66),
new Integer(32), new Integer(98), new Boolean(false),new Boolean(false)},
{"阿瓜", new Integer(85),
new Integer(69), new Integer(154), new Boolean(true),new Boolean(false)},
};
String[] n = {"姓名",
"语文",
"数学",
"总分",
"及格",
"作弊"};
public int getColumnCount() {
return n.length;
}
public int getRowCount() {
return p.length;
}
public String getColumnName(int col) {
return n[col];
}
public Object getValueAt(int row, int col) {
return p[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
import javax.swing.table.AbstractTableModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TableModel2 implements ActionListener{
JTable t = null;
public TableModel2() {
JFrame f = new JFrame("DataModel");
JButton b1 = new JButton("数学老师");
b1.addActionListener(this);
JButton b2 = new JButton("学生阿呆");
b2.addActionListener(this);
JPanel panel = new JPanel();
panel.add(b1);
panel.add(b2);
t=new JTable(new MyTable(1));
t.setPreferredScrollableViewportSize(new Dimension(550, 30));
JScrollPane s = new JScrollPane(t);
f.getContentPane().add(panel, BorderLayout.NORTH);
f.getContentPane().add(s, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("学生阿呆"))
t.setModel(new MyTable(1));
if (e.getActionCommand().equals("数学老师"))
t.setModel(new MyTable(2));
t.revalidate();
}
public static void main(String args[]) {
new TableModel2();
}
}
class MyTable extends AbstractTableModel{
Object[][] p1 = {
{"阿呆", "1234",new Integer(66),
new Integer(50), new Integer(116), new Boolean(false),new Boolean(false)}};
String[] n1 = {"姓名","学号","语文","数学","总分","及格","作弊"};
Object[][] p2 = {
{"阿呆", "1234",new Integer(50), new Boolean(false),new Boolean(false),"01234"},
{"阿瓜", "1235",new Integer(75), new Boolean(true),new Boolean(false),"05678"}};
String[] n2 = {"姓名","学号","数学","及格","作弊","电话"};
int model = 1;
public MyTable(int i){
model = i;
}
public int getColumnCount() {
if(model ==1)
return n1.length;
else
return n2.length;
}
public int getRowCount() {
if(model ==1)
return p1.length;
else
return p2.length;
}
public String getColumnName(int col) {
if(model ==1)
return n1[col];
else
return n2[col];
}
public Object getValueAt(int row, int col) {
if(model == 1)
return p1[row][col];
else
return p2[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
import javax.swing.table.AbstractTableModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColumnModelTest{
public ColumnModelTest() {
JFrame f = new JFrame();
/*由于我们的MyTable类继承了AbstractTableModel并且实作了getColmunCount(),getRowCount(),getValueAt()方法.因此我们可以通
*过MyTable来产生TableModel的实体.
*/
MyTable mt=new MyTable();
JTable t=new JTable(mt);//我们利用MyTable来建立JTable.
JComboBox c = new JComboBox();//建立一个JComboBox的对象.
c.addItem("Taipei");//我们在新建立的JComboBox对象里新增三个项目.
c.addItem("ChiaYi");
c.addItem("HsinChu");
/*我们利用JTable所提供的getTableColumnModel()方法取得TableColumnModel对象,再由TableColumnModel类所提供的getColumn()方
*法取得TableColumn对象,TableColumn类可针对表格中的每一行做具体的设置,例如设置字段的宽度,某行的标头,设置输入较复杂的
*数据类型等等.在这里,我们利用TableColumn类所提供的setCellEditor()方法,将JComboBox作为第二行的默认编辑组件.
*/
t.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(c));
t.setPreferredScrollableViewportSize(new Dimension(550, 30));
JScrollPane s = new JScrollPane(t);
f.getContentPane().add(s, BorderLayout.CENTER);
f.setTitle("ColumnModelTest");
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String args[]) {
new ColumnModelTest();
}
}
class MyTable extends AbstractTableModel{
Object[][] p = {
{"阿呆", "Taipei",new Integer(66),
new Integer(32), new Integer(98), new Boolean(false),new Boolean(false)},
{"阿瓜", "ChiaYi",new Integer(85),
new Integer(69), new Integer(154), new Boolean(true),new Boolean(false)},
};
String[] n = {"姓名",
"居住地",
"语文",
"数学",
"总分",
"及格",
"作弊"};
public int getColumnCount() {
return n.length;
}
public int getRowCount() {
return p.length;
}
public String getColumnName(int col) {
return n[col];
}
public Object getValueAt(int row, int col) {
return p[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
public void setValueAt(Object value, int row, int col) {
p[row][col] = value;
fireTableCellUpdated(row, col);
}*/
}
public void setValueAt(Object value,int row,int col){
p[row][col]=value;
fireTableCellUpdated(row,col);
}
import java.awt.*;说明:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SelectionModelDemo implements ActionListener,ListSelectionListener{
JTable table=null;
ListSelectionModel selectionMode=null;
JLabel label=null;//显示用户选取表格之用
public SelectionModelDemo(){
JFrame f=new JFrame();
String[] name={"字段1","字段2","字段3","字段4","字段5"};
String[][] data=new String[5][5];
int value=1;
for(int i=0;i<data.length;i++){
for (int j=0;j<data.length;j++){
data[j]=String.valueOf(value++);
}
}
table=new JTable(data,name);
table.setPreferredScrollableViewportSize(new Dimension(400,80));
table.setCellSelectionEnabled(true);//使得表格的选取是以cell为单位,而不是以列为单位.若你没有写此行,则在选取表格数
//据时以整列为单位.
selectionMode=table.getSelectionModel();//取得table的ListSelectionModel.
selectionMode.addListSelectionListener(this);
JScrollPane s=new JScrollPane(table);
JPanel panel=new JPanel();
JButton b=new JButton("单一选择");
panel.add(b);
b.addActionListener(this);
b=new JButton("连续区间选择");
panel.add(b);
b.addActionListener(this);
b=new JButton("多重选择");
panel.add(b);
b.addActionListener(this);
label=new JLabel("你选取:");
Container contentPane=f.getContentPane();
contentPane.add(panel,BorderLayout.NORTH);
contentPane.add(s,BorderLayout.CENTER);
contentPane.add(label,BorderLayout.SOUTH);
f.setTitle("SelectionModelDemo");
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/*处理按钮事件,利用ListSelectionModel界面所定义的setSelectionMode()方法来设置表格选取模式.*/
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("单一选择"))
selectionMode.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (e.getActionCommand().equals("连续区间选择"))
selectionMode.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
if (e.getActionCommand().equals("多重选择"))
selectionMode.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.revalidate();
}
/*当用户选取表格数据时会触发ListSelectionEvent,我们实现ListSelectionListener界面来处理这一事件.ListSelectionListener界
*面只定义一个方法,那就是valueChanged().
*/
public void valueChanged(ListSelectionEvent el){
String tempString="";
//JTable的getSelectedRows()与getSelectedColumns()方法会返回已选取表格cell的index Array数据.
int[] rows=table.getSelectedRows();
int[] columns=table.getSelectedColumns();
//JTable的getValueAt()方法会返回某行的cell数据,返回值是Object数据类型,因此我们要自行转成String数据类型.
for (int i=0;i<rows.length;i++){
for (int j=0;j<columns.length;j++)
tempString = tempString+" "+(String)table.getValueAt(rows, columns[j]);
}
label.setText("你选取:"+tempString);
}
public static void main(String[] args){
new SelectionModelDemo();
}
}
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class AddRemoveCells implements ActionListener
{
JTable table = null;
DefaultTableModel defaultModel = null;
public AddRemoveCells()
{
JFrame f = new JFrame();
String[] name = {"字段 1","字段 2","字段 3","字段 4","字段 5"};
String[][] data = new String[5][5];
int value =1;
for(int i=0; i<data.length; i++)
{
for(int j=0; j<data.length ; j++)
data[j] = String.valueOf(value++);
}
defaultModel = new DefaultTableModel(data,name);
table=new JTable(defaultModel);
table.setPreferredScrollableViewportSize(new Dimension(400, 80));
JScrollPane s = new JScrollPane(table);
JPanel panel = new JPanel();
JButton b = new JButton("增加行");
panel.add(b);
b.addActionListener(this);
b = new JButton("增加列");
panel.add(b);
b.addActionListener(this);
b = new JButton("删除行");
panel.add(b);
b.addActionListener(this);
b = new JButton("删除列");
panel.add(b);
b.addActionListener(this);
Container contentPane = f.getContentPane();
contentPane.add(panel, BorderLayout.NORTH);
contentPane.add(s, BorderLayout.CENTER);
f.setTitle("AddRemoveCells");
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/*要删除列必须使用TableColumnModel界面定义的removeColumn()方法。因此我闪先由JTable类的getColumnModel()方法取得
*TableColumnModel对象,再由TableColumnModel的getColumn()方法取得要删除列的TableColumn.此TableColumn对象当作是
*removeColumn()的参数。删除此列完毕后必须重新设置列数,也就是使用DefaultTableModel的setColumnCount()方法来设置。
*/
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("增加列"))
defaultModel.addColumn("增加列");
if(e.getActionCommand().equals("增加行"))
defaultModel.addRow(new Vector());
if(e.getActionCommand().equals("删除列"))
{
int columncount = defaultModel.getColumnCount()-1;
if(columncount >= 0)//若columncount<0代表已经没有任何列了。
{
TableColumnModel columnModel = table.getColumnModel();
TableColumn tableColumn = columnModel.getColumn(columncount);
columnModel.removeColumn(tableColumn);
defaultModel.setColumnCount(columncount);
}
}
if(e.getActionCommand().equals("删除行"))
{
int rowcount = defaultModel.getRowCount()-1;//getRowCount返回行数,rowcount<0代表已经没有任何行了。
if(rowcount >= 0)
{
defaultModel.removeRow(rowcount);
defaultModel.setRowCount(rowcount);//删除行比较简单,只要用DefaultTableModel的removeRow()方法即可。删除
//行完毕后必须重新设置列数,也就是使用DefaultTableModel的setRowCount()方法来设置。
}
}
table.revalidate();
}
public static void main(String args[]) {
new AddRemoveCells();
}
}