JTable中实现行背景颜色、固定表格列宽、根据内容自动调整列宽、列中数据排序等功能示例代码

信息资料来源:根据以下两链接内容进行整理。在此对两文章作者表示感谢!

http://hi.baidu.com/leeyesong/blog/item/427442d04f5aaf8ba0ec9cd5.html

http://lyh7609.javaeye.com/blog/466380

(1)StyleTable.java文件用于实现各种上面提到的功能。

  1 import java.awt.Color;
2 import java.awt.Component;
3 import java.awt.Dimension;
4 import java.util.Enumeration;
5 import javax.swing.JTable;
6 import javax.swing.RowSorter;
7 import javax.swing.table.DefaultTableCellRenderer;
8 import javax.swing.table.JTableHeader;
9 import javax.swing.table.TableColumn;
10 import javax.swing.table.TableColumnModel;
11 import javax.swing.table.TableModel;
12 import javax.swing.table.TableRowSorter;
13
14 /**
15 * 本类实现了对JTable颜色的控制,提供了两套方案:
16 * 1.实现了表格行两种颜色交替的效果
17 * 2.实现了用一个控制颜色的字符串数组来设置所对应行的颜色
18 * 本文件与PlanetTable.java文件相配合使用
19 * @author Sidney
20 * @version 1.0 (2008-1-14)
21 */
22 public class StyleTable extends JTable {
23 private String[] color = null; //用于设定行颜色的数组
24
25 public StyleTable() {
26 super();
27 }
28
29 public StyleTable(Object[][] rowData, Object[] columnNames) {
30 super(rowData, columnNames);
31 paintRow(); //将奇偶行分别设置为不同颜色
32
33 //setFixColumnWidth(this); //固定表格的列宽
34
35 //通过点击表头来排序列中数据resort data by clicking table header
36 RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.getModel());
37 this.setRowSorter(sorter);
38
39 this.setIntercellSpacing(new Dimension(5,5)); //设置数据与单元格边框的眉边距
40
41 //根据单元内的数据内容自动调整列宽resize column width accordng to content of cell automatically
42 fitTableColumns(this);
43 }
44
45 public StyleTable(Object[][] rowData, Object[] columnNames, String[] color) {
46 super(rowData, columnNames);
47 this.color = color;
48 paintColorRow();
49
50 setFixColumnWidth(this);
51
52 RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.getModel());
53 this.setRowSorter(sorter);
54
55 this.setIntercellSpacing(new Dimension(5,5));
56
57 fitTableColumns(this);
58 }
59
60 /**
61 * 根据color数组中相应字符串所表示的颜色来设置某行的颜色,注意,JTable中可以对列进行整体操作
62 * 而无法对行进行整体操作,故设置行颜色实际上是逐列地设置该行所有单元格的颜色。
63 */
64 public void paintRow() {
65 TableColumnModel tcm = this.getColumnModel();
66 for (int i = 0, n = tcm.getColumnCount(); i < n; i++) {
67 TableColumn tc = tcm.getColumn(i);
68 tc.setCellRenderer(new RowRenderer());
69 }
70 }
71
72 public void paintColorRow() {
73 TableColumnModel tcm = this.getColumnModel();
74 for (int i = 0, n = tcm.getColumnCount(); i < n; i++) {
75 TableColumn tc = tcm.getColumn(i);
76 tc.setCellRenderer(new RowColorRenderer());
77 }
78 }
79
80 /**
81 * 将列设置为固定宽度。//fix table column width
82 *
83 */
84 public void setFixColumnWidth(JTable table) {
85 //this.setRowHeight(30);
86 this.setAutoResizeMode(table.AUTO_RESIZE_OFF);
87 /**/
88 //The following code can be used to fix table column width
89 TableColumnModel tcm = table.getTableHeader().getColumnModel();
90 for (int i = 0; i < tcm.getColumnCount(); i++) {
91 TableColumn tc = tcm.getColumn(i);
92 tc.setPreferredWidth(50);
93 // tc.setMinWidth(100);
94 tc.setMaxWidth(50);
95 }
96 }
97
98 /**
99 * 根据数据内容自动调整列宽。//resize column width automatically
100 *
101 */
102 public void fitTableColumns(JTable myTable) {
103 myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
104 JTableHeader header = myTable.getTableHeader();
105 int rowCount = myTable.getRowCount();
106 Enumeration columns = myTable.getColumnModel().getColumns();
107 while(columns.hasMoreElements()) {
108 TableColumn column = (TableColumn)columns.nextElement();
109 int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
110 int width = (int)header.getDefaultRenderer().getTableCellRendererComponent
111 (myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth();
112 for(int row = 0; row < rowCount; row++) {
113 int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent
114 (myTable, myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
115 width = Math.max(width, preferedWidth);
116 }
117 header.setResizingColumn(column); // 此行很重要
118 column.setWidth(width+myTable.getIntercellSpacing().width);
119 }
120 }
121
122 /**
123 * 定义内部类,用于控制单元格颜色,每两行颜色相间,本类中定义为蓝色和绿色。
124 *
125 * @author Sidney
126 *
127 */
128 private class RowRenderer extends DefaultTableCellRenderer {
129 public Component getTableCellRendererComponent(JTable t, Object value,
130 boolean isSelected, boolean hasFocus, int row, int column) {
131 //设置奇偶行的背景色,可在此根据需要进行修改
132 if (row % 2 == 0)
133 setBackground(Color.BLUE);
134 else
135 setBackground(Color.GREEN);
136
137 return super.getTableCellRendererComponent(t, value, isSelected,
138 hasFocus, row, column);
139 }
140 }
141
142 /**
143 * 定义内部类,可根据一个指定字符串数组来设置对应行的背景色
144 *
145 * @author Sidney
146 *
147 */
148 private class RowColorRenderer extends DefaultTableCellRenderer {
149 public Component getTableCellRendererComponent(JTable t, Object value,
150 boolean isSelected, boolean hasFocus, int row, int column) {
151 //分支判断条件可根据需要进行修改
152 if (color[row].trim().equals("E")) {
153 setBackground(Color.RED);
154 }
155 else if (color[row].trim().equals("H")) {
156 setBackground(Color.CYAN);
157 }
158 else if (color[row].trim().equals("A")) {
159 setBackground(Color.BLUE);
160 }
161 else if (color[row].trim().equals("F")) {
162 setBackground(Color.ORANGE);
163 }
164 else {
165 setBackground(Color.WHITE);
166 }
167
168 return super.getTableCellRendererComponent(t, value, isSelected,
169 hasFocus, row, column);
170 }
171 }
172 }

(2)PlanetTable.java文件用于利用上面的实现展示功能。

 1 import java.awt.BorderLayout;
2 import java.awt.Color;
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import javax.swing.JButton;
6 import javax.swing.JFrame;
7 import javax.swing.JPanel;
8 import javax.swing.JScrollPane;
9 import javax.swing.JTable;
10
11 /**
12 * 本类为JTable一个简单应用,实现了JTable的行颜色设置及表格的打印功能
13 * 本文件与StyleTable.java文件相配合使用
14 */
15 public class PlanetTable {
16 public static void main(String[] args) {
17 JFrame frame = new PlanetTableFrame();
18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19 frame.setVisible(true);
20 }
21 }
22
23 class PlanetTableFrame extends JFrame {
24 private Object[][] cells = {
25 { "Mercury", new Double(2440.0), new Integer(0),
26 new Boolean(false), Color.yellow },
27 { "Venus", new Double(60520.0), new Integer(0), new Boolean(false),
28 Color.yellow },
29 { "Earth", new Double(6378.0), new Integer(1), new Boolean(false),
30 Color.blue },
31 { "Mars", new Double(3397.0), new Integer(2), new Boolean(false),
32 Color.red },
33 { "Jupiter", new Double(71492.0), new Integer(16),
34 new Boolean(false), Color.orange } };
35
36 private String[] columnNames = { "Planet", "Radius", "Moons", "Gaseous",
37 "Color" };
38
39 private static final int DEFAULT_WIDTH = 400;
40 private static final int DEFAULT_HEIGHT = 200;
41
42 public PlanetTableFrame() {
43 // 用于控制每一行颜色的数组
44 String[] color = { "H", "A", "F", "E", "W" };
45
46 setTitle("PlanetTable");
47 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
48 // 定义JTable,实例成自己扩展的JTable类,并传入用于设定颜色的数组
49 //final JTable table = new StyleTable(cells, columnNames, color);
50 // 下面这行代码可实现相邻两行颜色交替的效果,注意与上一行的区别
51 final JTable table = new StyleTable(cells, columnNames);
52 add(new JScrollPane(table), BorderLayout.CENTER);
53
54 JButton printButton = new JButton("Print");
55 printButton.addActionListener(new ActionListener() {
56 public void actionPerformed(ActionEvent event) {
57 try {
58 table.print();
59 } catch (java.awt.print.PrinterException e) {
60 e.printStackTrace();
61 }
62 }
63 });
64 JPanel buttonPanel = new JPanel();
65 buttonPanel.add(printButton);
66 add(buttonPanel, BorderLayout.SOUTH);
67 }
68 }

效果图如下(根据代码微调会使效果图不同):

posted @ 2010-03-23 10:04  可微  阅读(9330)  评论(0编辑  收藏  举报