JTable中合并
格
/*
* SimpleTableDemo.java is a 1.4 application that requires no other files.
*/
//编辑的时候直接从覆盖原有内容
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;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.io.*;
import java.util.*;
public class Combine extends JPanel {
private boolean DEBUG = false;
JTable table;
public Combine() {
super(new GridLayout(1,0));
table = new JTable( new MyTableModel() );
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
///////////////////////////////////////////////////////////
table.setDefaultEditor( String.class, new SelEditor() );
//Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
/**
* Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread.
*/
private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("MyCustomTable2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Combine newContentPane = new Combine(); newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
try
{
Thread.sleep( 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
((MyTableModel)newContentPane.table.getModel()).combineRow( "First Name", "Last Name" );
}
public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application?s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {
createAndShowGUI();
}
});
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name", "Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private List cList = new ArrayList(); {
for( int i = 0; i < columnNames.length; i ++ ) cList.add( columnNames[ i ] );
}
private Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)} };
private List dList = new ArrayList(); {
for( int i = 0; i < data.length; i ++ ) { List tmp = new ArrayList();
for( int j = 0; j < data[ i ].length; j ++ ) { tmp.add( data[ i ][ j ] );
}
dList.add( tmp );
}
}
public int getColumnCount() {
return cList.size();
}
public int getRowCount() {
return dList.size();
}
public String getColumnName(int col) {
return (String)cList.get( col );
}
public Object getValueAt(int row, int col) { return ((List)dList.get( row )).get( col ); }
public void combineRow( String r1, String r2 ) { int index1 = cList.indexOf( r1 );
int index2 = cList.indexOf( r2 );
cList.set( index1, r1+r2 );
cList.remove( r2 );
for( int i = 0; i < dList.size(); i ++ ) { List list = (List)dList.get( i );
list.set( index1, list.get( index1 ).toString() + list.get( index2 ) );
list.remove( index2 );
}
fireTableStructureChanged();
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn?t implement this method, * then the last column would contain text ("true"/"false"), * rather than a check box.
*/
public Class getColumnClass(int c) {
return cList.get( c ).getClass();
}
public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen.
return true;
}
public void setValueAt(Object value, int row, int col) {
((List)dList.get( row )).set( col , value ); fireTableCellUpdated(row, col);
}
private void printDebugData() { int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) { System.out.print(" row " + i + ":"); for (int j=0; j < numCols; j++) { System.out.print(" " + ((List)dList.get( i )).get( j ));
}
System.out.println();
}
System.out.println("--------------------------");
}
}
}
请仔细看MyTableModel的实现
第二个:
/* (swing1.1beta3) */
package tame.examples;
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import tame.table.ColumnGroup;
import tame.table.GroupableTableHeader;
import tame.table.GroupableTableHeaderUI;
/**
* |-----------------------------------------------------| * | | Name | Language | * | |-----------------|--------------------------| * | SNo. | | | | Others | * | | 1 | 2 | Native |-----------------| * | | | | | 2 | 3 | * |-----------------------------------------------------| * | | | | | | |
@author Nobuo Tamemasa
@version 1.0 11/09/98
*/
public class GroupableHeaderExample extends JFrame {
GroupableHeaderExample() {
super( "Groupable Header Example" );
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{
{"119","foo","bar","ja","ko","zh"},
{"911","bar","foo","en","fr","pt"}},
new Object[]{"SNo.","1","2","Native","2","3"});
JTable table = new JTable( dm ) {
protected JTableHeader createDefaultTableHeader() {
return new GroupableTableHeader(columnModel);
}
};
TableColumnModel cm = table.getColumnModel(); //得到列模型,可
以取出
头
ColumnGroup g_name = new ColumnGroup("Name");
g_name.add(cm.getColumn(1));
g_name.add(cm.getColumn(2));
ColumnGroup g_lang = new ColumnGroup("Language");
g_lang.add(cm.getColumn(3));
ColumnGroup g_other = new ColumnGroup("Others");
g_other.add(cm.getColumn(4));
g_other.add(cm.getColumn(5));
g_lang.add(g_other);
GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
header.addColumnGroup(g_name);
header.addColumnGroup(g_lang);
TableCellRenderer renderer = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JTableHeader header = table.getTableHeader();
if (header != null) {
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
setHorizontalAlignment(JLabel.CENTER);
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
}
};
TableColumnModel model = table.getColumnModel();
for (int i=0;i
题了,而后面重复累加了此m
argin。你可以更改GroupableTableHeaderUI的paint方法,删除对margin的
累加。
本来我已经看到这种不能对齐的情况,没想到你真的来问。不过我还是鼓励你自
己解决,实在不行的话,在来此问。
具体代码如下:
public void paint(Graphics g, JComponent c) {
Rectangle clipBounds = g.getClipBounds();
if (header.getColumnModel() == null) return;
// ((GroupableTableHeader)header).setColumnMargin();
int column = 0;
Dimension size = header.getSize();
Rectangle cellRect = new Rectangle(0, 0, size.width, size.height);
Hashtable h = new Hashtable();
// int columnMargin = header.getColumnModel().getColumnMargin();
Enumeration enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
cellRect.height = size.height;
cellRect.y = 0;
TableColumn aColumn = (TableColumn)enumeration.nextElement();
Enumeration cGroups = ((GroupableTableHeader)header).getColumnGroups(aColumn);
if (cGroups != null) {
int groupHeight = 0;
while (cGroups.hasMoreElements()) {
ColumnGroup cGroup = (ColumnGroup)cGroups.nextElement();
Rectangle groupRect = (Rectangle)h.get(cGroup);
if (groupRect == null) {
groupRect = new Rectangle(cellRect);
Dimension d = cGroup.getSize(header.getTable());
groupRect.width = d.width;
groupRect.height = d.height;
h.put(cGroup, groupRect);
}
paintCell(g, groupRect, cGroup);
groupHeight += groupRect.height;
cellRect.height = size.height - groupHeight;
cellRect.y = groupHeight;
}
}
cellRect.width = aColumn.getWidth() ;//+ columnMargin;
if (cellRect.intersects(clipBounds)) {
paintCell(g, cellRect, column);
}
cellRect.x += cellRect.width;
column++;
}
}
——————————————————————————————————
——————————————————
在AttributiveCellTableMode中暂时把setDataVector方法的内容用下面的代
码替代:
public void setDataVector(Vector newData, Vector columnNames) {
if (newData == null)
throw new IllegalArgumentException("setDataVector() - Null parameter");
dataVector = (newData != null) ? newData : new Vector(0);
columnIdentifiers = (columnNames != null) ? columnNames : new Vector(0);
cellAtt = new DefaultCellAttribute(dataVector.size(),
columnIdentifiers.size());
newRowsAdded(new TableModelEvent(this, 0, getRowCount()-1,
TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
}
关于对