swing jtable 合并


swing jtable 合并

 

import java.awt.Component;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class Test extends JFrame
{
	Object[][] data = null;
	/*
	 * We create an Array String to hold the name of the main table columns In
	 * this example case we are going to store a contact name, his email
	 * address(es) and his phone numer(s) We’re also going to store the creation
	 * date.
	 */
	String[] columns =
	{ "name", "mail", "phome", "date" };
	JTable jTableData;

	Test()
	{
		jTableData = new JTable();
		data = new Object[3][columns.length];
		data[0][0] = "Peter";
		String[] emails =
		{ "[email protected]", "[email protected]" };
		data[0][1] = emails;
		String[] phones =
		{ "333", "444" };
		data[0][2] = phones;
		data[0][3] = new Date();
		data[1][0] = "Jackson";
		data[1][1] = "[email protected]";
		String[] phones2 =
		{ "3333", "5555", "7777" };
		data[1][2] = phones2;
		data[1][3] = new Date();
		data[2][0] = "Robert";
		data[2][1] = "[email protected]";
		data[2][2] = "1357";
		data[2][3] = new Date();
		AbstractTableModel modelo = new AbstractTableModel()
		{
			public String getColumnName(int col)
			{
				return columns[col].toString();
			}

			public Class getColumnClass(int col)
			{
				if (getRowCount() < 1)
					return null;
				return data[0][col].getClass();
			}

			public int getRowCount()
			{
				return data.length;
			}

			public int getColumnCount()
			{
				return columns.length;
			}

			public Object getValueAt(int row, int col)
			{
				return data[row][col];
			}

			public boolean isCellEditable(int row, int col)
			{
				return true;
			}

			public void setValueAt(Object value, int row, int col)
			{
				data[row][col] = value;
				fireTableCellUpdated(row, col);
			}
		};
		/* We apply the model to the main jTable */
		jTableData.setModel(modelo);
		/*
		 * We create a cell Renderer to display the data of the multivalue
		 * fields
		 */
		TableCellRenderer jTableCellRenderer = new TableCellRenderer()
		{
			/* These are necessary variables to store the row’s height */
			private int minHeight = -1;
			private int currHeight = -1;

			/* Magic Happens */
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column)
			{
				/*
				 * If what we’re displaying isn’t an array of values we return
				 * the normal renderer
				 */
				if (!value.getClass().isArray())
				{
					return table.getDefaultRenderer(value.getClass())
							.getTableCellRendererComponent(table, value,
									isSelected, hasFocus, row, column);
				}
				else
				{
					final Object[] passed = (Object[]) value;
					/*
					 * We calculate the row’s height to display data THis is not
					 * complete and has some bugs that will be analyzed in
					 * further articles
					 */
					if (minHeight == -1)
					{
						minHeight = table.getRowHeight();
					}
					if (currHeight != passed.length * minHeight)
					{
						currHeight = passed.length * minHeight;
						table.setRowHeight(row, currHeight);
					}
					/*
					 * We create the table that will hold the multivalue fields
					 * and that will be embedded in the main table
					 */
					return new JTable(new AbstractTableModel()
					{
						public int getColumnCount()
						{
							return 1;
						}

						public int getRowCount()
						{
							return passed.length;
						}

						public Object getValueAt(int rowIndex, int columnIndex)
						{
							return passed[rowIndex];
						}

						public boolean isCellEditable(int row, int col)
						{
							return true;
						}
					});
				}
			}
		};
		/* Finally we apply the new cellRenderer to the whole table */
		TableColumnModel tcm = jTableData.getColumnModel();
		for (int it = 0; it < tcm.getColumnCount(); it++)
		{
			tcm.getColumn(it).setCellRenderer(jTableCellRenderer);
		}
		/*
		 * Note: if we need to edit the values inside the embedded jtable we
		 * will need to create a TableCellEditor too.
		 */
		add(new JScrollPane(jTableData));
		setSize(400, 400);
		setLocationRelativeTo(null);
	}

	public static void main(String a[])
	{
		new Test().setVisible(true);
	}
}

 

 


swing jtable 合并
 import java.awt.Color;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.plaf.TableUI;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class Test1 extends JFrame
{
	Object[][] data = null;
	
	String[] columns = { "ID", "TITLE", "RECURRENT", "PRICE","DATE" };
	JTable jTableData;

	Test1()
	{
		jTableData = new JTable(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			
			@Override
			public void setUI(TableUI ui)
			{
				// TODO Auto-generated method stub
				super.setUI(new BasicTableUI(){
					 public void paint(Graphics g, JComponent c) { 
						    Rectangle r=g.getClipBounds(); 
						    int firstRow=table.rowAtPoint(new Point(0,r.y)); 
						    int lastRow=table.rowAtPoint(new Point(0,r.y+r.height)); 
						    // -1 is a flag that the ending point is outside the table 
						    if (lastRow<0) 
						         lastRow=table.getRowCount()-1; 
						    for (int i=firstRow; i<=lastRow; i++) 
						              paintRow(i,g); 
						  } 
						  private void paintRow(int row, Graphics g) 
						  { 
						    Rectangle r=g.getClipBounds(); 
						    for (int i=0; i<table.getColumnCount();i++) 
						    { 
						      Rectangle r1=table.getCellRect(row,i,true); 
						      if (r1.intersects(r)) // at least a part is visible 
						      { 
						        int sk=i;//((CTable)table).map.visibleCell(red,i); 
						        paintCell(row,sk,g,r1); 
						        // increment the column counter 
						        //i+=((CTable)table).map.span(row,sk)-1; 
						        //i++;
						      } 
						    } 
						  } 
						  private void paintCell(int row, int column, Graphics g,Rectangle area) 
						  { 
						    int verticalMargin = table.getRowMargin(); 
						    int horizontalMargin  = table.getColumnModel().getColumnMargin(); 
						  
						    Color c = g.getColor(); 
						    g.setColor(table.getGridColor()); 
						    g.drawRect(area.x,area.y,area.width-1,area.height-1); 
						    g.setColor(c); 
						  
						    area.setBounds(area.x + horizontalMargin/2, 
						                  area.y + verticalMargin/2, 
						                    area.width - horizontalMargin, 
						                  area.height - verticalMargin); 
						  
						    if (table.isEditing() && table.getEditingRow()==row && 
						         table.getEditingColumn()==column) 
						    { 
						      Component component = table.getEditorComponent(); 
						      component.setBounds(area); 
						      component.validate(); 
						    } 
						    else 
						     { 
						      TableCellRenderer renderer = table.getCellRenderer(row, column); 
						      Component component = table.prepareRenderer(renderer, row, column); 
						      if (component.getParent() == null) 
						         rendererPane.add(component); 
						     rendererPane.paintComponent(g, component, table, area.x, area.y, 
						     area.width, area.height, true); 
						    } 
						  } 
				});
			}
			
			@Override
			public Rectangle getCellRect(int row, int column,
					boolean includeSpacing)
			{
				if(row==1||row==3)
				{
					System.out.println("row="+row);
					
					Rectangle rect = new Rectangle(0, this.getRowHeight() * row, this
							.getWidth(), this.getRowHeight());
				
					//repaint();
					System.out.println(row);
					System.out.println(rect.getX());
					System.out.println(rect.getY());
					System.out.println(rect.getWidth());
					System.out.println(rect.getHeight());
					System.out.println("===============");
					return rect;
				}
				
				return super.getCellRect(row, column, includeSpacing);
			}
			
		};
		data = new Object[6][columns.length];
		data[0][0] = "1";
		String pr1 = "product1";
		data[0][1] = pr1;
		String title = "test";
		data[0][2] = title;
		data[0][3] = title;
		data[0][4] = title;
		
		data[1][0] = "product21";
		data[1][1] = "product21";
		data[1][2] = "product21";
		data[1][3] = "product21";
		data[1][4] = "product21";
		
		data[2][0] = "3";
		data[2][1] = "product3";
		data[2][2] = "31";
		data[2][3] = "32";
		data[2][4] = "33";
		
		data[3][0] = "product44";
		data[3][1] = "product44";
		data[3][2] = "product44";
		data[3][3] = "product44";
		data[3][4] = "product44";
		
		data[4][0] = "5";
		data[4][1] = "product5";
		data[4][2] = "51";
		data[4][3] = "52";
		data[4][4] = "53";
		
		data[5][0] = "6";
		data[5][1] = "product6";
		data[5][2] = "61";
		data[5][3] = "62";
		data[5][4] = "63";
		
		
		
		AbstractTableModel model = new AbstractTableModel()
		{
			public String getColumnName(int col)
			{
				return columns[col].toString();
			}

			public Class getColumnClass(int col)
			{
				if (getRowCount() < 1)
					return null;
				return data[0][col].getClass();
			}

			public int getRowCount()
			{
				return data.length;
			}

			public int getColumnCount()
			{
				return columns.length;
			}

			public Object getValueAt(int row, int col)
			{
				return data[row][col];
			}

			public boolean isCellEditable(int row, int col)
			{
				return false;
			}

			public void setValueAt(Object value, int row, int col)
			{
				data[row][col] = value;
				fireTableCellUpdated(row, col);
			}
		};
		/* We apply the model to the main jTable */
		jTableData.setModel(model);
		
		add(new JScrollPane(jTableData));
		setSize(400, 400);
		setLocationRelativeTo(null);
	}

	public static void main(String a[])
	{
		new Test1().setVisible(true);
	}
}
 

 

 

 

 

 

~~~~~~~~~~~~~~~~~~~~~

 

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.plaf.TableUI;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class Test1 extends JFrame
{
	Object[][] data = null;
	
	String[] columns = { "ID", "TITLE", "RECURRENT", "PRICE","DATE" };
	JTable jTableData;

	Test1()
	{
		jTableData = new JTable(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			
			@Override
			public void setUI(TableUI ui)
			{
				// TODO Auto-generated method stub
				super.setUI(new BasicTableUI(){
					 public void paint(Graphics g, JComponent c) { 
						    Rectangle r=g.getClipBounds(); 
						    int firstRow=table.rowAtPoint(new Point(0,r.y)); 
						    int lastRow=table.rowAtPoint(new Point(0,r.y+r.height)); 
						    // -1 is a flag that the ending point is outside the table 
						    if (lastRow<0) 
						         lastRow=table.getRowCount()-1; 
						    for (int i=firstRow; i<=lastRow; i++) 
						              paintRow(i,g); 
						  } 
						  private void paintRow(int row, Graphics g) 
						  { 
						    Rectangle r=g.getClipBounds(); 
						    for (int i=0; i<table.getColumnCount();i++) 
						    { 
						      Rectangle r1=table.getCellRect(row,i,true); 
						      if (r1.intersects(r)) // at least a part is visible 
						      { 
						        int sk=i;//((CTable)table).map.visibleCell(red,i); 
						        paintCell(row,sk,g,r1); 
						        // increment the column counter 
						        //i+=((CTable)table).map.span(row,sk)-1; 
						        //i++;
						      } 
						    } 
						  } 
						  private void paintCell(int row, int column, Graphics g,Rectangle area) 
						  { 
						    int verticalMargin = table.getRowMargin(); 
						    int horizontalMargin  = table.getColumnModel().getColumnMargin(); 
						  
						    Color c = g.getColor(); 
						    g.setColor(table.getGridColor()); 
						    g.drawRect(area.x,area.y,area.width-1,area.height-1); 
						    g.setColor(c); 
						  
						    area.setBounds(area.x + horizontalMargin/2, 
						                  area.y + verticalMargin/2, 
						                    area.width - horizontalMargin, 
						                  area.height - verticalMargin); 
						  
						    if (table.isEditing() && table.getEditingRow()==row && 
						         table.getEditingColumn()==column) 
						    { 
						      Component component = table.getEditorComponent(); 
						      component.setBounds(area); 
						      component.validate(); 
						    } 
						    else 
						     { 
						      TableCellRenderer renderer = table.getCellRenderer(row, column); 
						      Component component = table.prepareRenderer(renderer, row, column); 
						      if (component.getParent() == null) 
						         rendererPane.add(component); 
						     rendererPane.paintComponent(g, component, table, area.x, area.y, 
						     area.width, area.height, true); 
						    } 
						  } 
				});
			}
			
			@Override
			public Rectangle getCellRect(int row, int column,
					boolean includeSpacing)
			{
				if(row==1||row==3)
				{
					System.out.println("row="+row);
					
					Rectangle rect = new Rectangle(0, this.getRowHeight() * row, this
							.getWidth(), this.getRowHeight());
				
					//repaint();
					System.out.println(row);
					System.out.println(rect.getX());
					System.out.println(rect.getY());
					System.out.println(rect.getWidth());
					System.out.println(rect.getHeight());
					System.out.println("===============");
					return rect;
				}
				
				return super.getCellRect(row, column, includeSpacing);
			}
			
		};
		data = new Object[6][columns.length];
		data[0][0] = "1";
		String pr1 = "product1";
		data[0][1] = pr1;
		String title = "test";
		data[0][2] = title;
		data[0][3] = title;
		data[0][4] = title;
		
		data[1][0] = "product21";
		data[1][1] = "product21";
		data[1][2] = "product21";
		data[1][3] = "product21";
		data[1][4] = "product21";
		
		data[2][0] = "3";
		data[2][1] = "product3";
		data[2][2] = "31";
		data[2][3] = "32";
		data[2][4] = "33";
		
		data[3][0] = "product44";
		data[3][1] = "product44";
		data[3][2] = "product44";
		data[3][3] = "product44";
		data[3][4] = "product44";
		
		data[4][0] = "5";
		data[4][1] = "product5";
		data[4][2] = "51";
		data[4][3] = "52";
		data[4][4] = "53";
		
		data[5][0] = "6";
		data[5][1] = "product6";
		data[5][2] = "61";
		data[5][3] = "62";
		data[5][4] = "63";
		
		
		
		AbstractTableModel model = new AbstractTableModel()
		{
			public String getColumnName(int col)
			{
				return columns[col].toString();
			}

			public Class getColumnClass(int col)
			{
				if (getRowCount() < 1)
					return null;
				return data[0][col].getClass();
			}

			public int getRowCount()
			{
				return data.length;
			}

			public int getColumnCount()
			{
				return columns.length;
			}

			public Object getValueAt(int row, int col)
			{
				return data[row][col];
			}

			public boolean isCellEditable(int row, int col)
			{
				return false;
			}

			public void setValueAt(Object value, int row, int col)
			{
				data[row][col] = value;
				fireTableCellUpdated(row, col);
			}
		};
		/* We apply the model to the main jTable */
		jTableData.setModel(model);
		
		add(new JScrollPane(jTableData));
		setSize(400, 400);
		setLocationRelativeTo(null);
	}

	public static void main(String a[])
	{
		new Test1().setVisible(true);
	}
}
 

 


swing jtable 合并
 给Jtable行添加背景色

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.plaf.TableUI;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class Test1 extends JFrame
{
	Object[][] data = null;
	/*
	 * We create an Array String to hold the name of the main table columns In
	 * this example case we are going to store a contact name, his email
	 * address(es) and his phone numer(s) We’re also going to store the creation
	 * date.
	 */
	String[] columns =
	{ "ID", "TITLE", "RECURRENT", "PRICE","DATE" };
	JTable jTableData;

	Test1()
	{
		jTableData = new JTable(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			
			@Override
			public void setUI(TableUI ui)
			{
				// TODO Auto-generated method stub
				super.setUI(new BasicTableUI(){
					 public void paint(Graphics g, JComponent c) { 
						    Rectangle r=g.getClipBounds(); 
						    int firstRow=table.rowAtPoint(new Point(0,r.y)); 
						    int lastRow=table.rowAtPoint(new Point(0,r.y+r.height)); 
						    // -1 is a flag that the ending point is outside the table 
						    if (lastRow<0) 
						         lastRow=table.getRowCount()-1; 
						    for (int i=firstRow; i<=lastRow; i++) 
						              paintRow(i,g); 
						  } 
						  private void paintRow(int row, Graphics g) 
						  { 
						    Rectangle r=g.getClipBounds(); 
						    for (int i=0; i<table.getColumnCount();i++) 
						    { 
						      Rectangle r1=table.getCellRect(row,i,true); 
						      if (r1.intersects(r)) // at least a part is visible 
						      { 
						        int sk=i;//((CTable)table).map.visibleCell(red,i); 
						        paintCell(row,sk,g,r1); 
						        // increment the column counter 
						        //i+=((CTable)table).map.span(row,sk)-1; 
						        //i++;
						      } 
						    } 
						  } 
						  private void paintCell(int row, int column, Graphics g,Rectangle area) 
						  { 
						    int verticalMargin = table.getRowMargin(); 
						    int horizontalMargin  = table.getColumnModel().getColumnMargin(); 
						  
						    Color c = g.getColor(); 
						    g.setColor(table.getGridColor()); 
						    g.drawRect(area.x,area.y,area.width-1,area.height-1); 
						    g.setColor(c); 
						  
						    area.setBounds(area.x + horizontalMargin/2, 
						                  area.y + verticalMargin/2, 
						                    area.width - horizontalMargin, 
						                  area.height - verticalMargin); 
						  
						    if (table.isEditing() && table.getEditingRow()==row && 
						         table.getEditingColumn()==column) 
						    { 
						      Component component = table.getEditorComponent(); 
						      component.setBounds(area); 
						      component.validate(); 
						    } 
						    else 
						     { 
						      TableCellRenderer renderer = table.getCellRenderer(row, column); 
						      Component component = table.prepareRenderer(renderer, row, column); 
						      if (component.getParent() == null) 
						         rendererPane.add(component); 
						     rendererPane.paintComponent(g, component, table, area.x, area.y, 
						     area.width, area.height, true); 
						    } 
						  } 
				});
			}
			
			@Override
			public Rectangle getCellRect(int row, int column,
					boolean includeSpacing)
			{
				if(row==1||row==3)
				{
					System.out.println("row="+row);
					
					Rectangle rect = new Rectangle(0, this.getRowHeight() * row, this
							.getWidth(), this.getRowHeight());
				
					//repaint();
					System.out.println(row);
					System.out.println(rect.getX());
					System.out.println(rect.getY());
					System.out.println(rect.getWidth());
					System.out.println(rect.getHeight());
					System.out.println("===============");
					return rect;
				}
				
				return super.getCellRect(row, column, includeSpacing);
			}
			
		};
		data = new Object[6][columns.length];
		data[0][0] = "1";
		String pr1 = "product1";
		data[0][1] = pr1;
		String title = "test";
		data[0][2] = title;
		data[0][3] = title;
		data[0][4] = title;
		
		data[1][0] = "product21";
		data[1][1] = "product21";
		data[1][2] = "product21";
		data[1][3] = "product21";
		data[1][4] = "product21";
		
		data[2][0] = "3";
		data[2][1] = "product3";
		data[2][2] = "31";
		data[2][3] = "32";
		data[2][4] = "33";
		
		data[3][0] = "product44";
		data[3][1] = "product44";
		data[3][2] = "product44";
		data[3][3] = "product44";
		data[3][4] = "product44";
		
		data[4][0] = "5";
		data[4][1] = "product5";
		data[4][2] = "51";
		data[4][3] = "52";
		data[4][4] = "53";
		
		data[5][0] = "6";
		data[5][1] = "product6";
		data[5][2] = "61";
		data[5][3] = "62";
		data[5][4] = "63";
		
		
		
		AbstractTableModel modelo = new AbstractTableModel()
		{
			public String getColumnName(int col)
			{
				return columns[col].toString();
			}

			public Class getColumnClass(int col)
			{
				if (getRowCount() < 1)
					return null;
				return data[0][col].getClass();
			}

			public int getRowCount()
			{
				return data.length;
			}

			public int getColumnCount()
			{
				return columns.length;
			}

			public Object getValueAt(int row, int col)
			{
				return data[row][col];
			}

			public boolean isCellEditable(int row, int col)
			{
				return false;
			}

			public void setValueAt(Object value, int row, int col)
			{
				data[row][col] = value;
				fireTableCellUpdated(row, col);
			}
		};
		/* We apply the model to the main jTable */
		jTableData.setModel(modelo);
		/*
		 * We create a cell Renderer to display the data of the multivalue
		 * fields
		 */
		TableCellRenderer jTableCellRenderer = new TableCellRenderer()
		{
			/* These are necessary variables to store the row’s height */
			private int minHeight = -1;
			private int currHeight = -1;
			

			/* Magic Happens */
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column)
			{
				//setBorder(new EmptyBorder(0,0,0,0));
				
				
				/*
				 * If what we’re displaying isn’t an array of values we return
				 * the normal renderer
				 */
				if (!value.getClass().isArray())
				{
					Component  cell = table.getDefaultRenderer(value.getClass())
					.getTableCellRendererComponent(table, value,
							isSelected, hasFocus, row, column);
					if (row  == 1 || row == 3)
					{
						 cell.setBackground(Color.CYAN); 
					}
					else
					{
						cell.setBackground(Color.WHITE);
					}
					return cell;
				}
				else
				{
					final Object[] passed = (Object[]) value;
					/*
					 * We calculate the row’s height to display data THis is not
					 * complete and has some bugs that will be analyzed in
					 * further articles
					 */
					if (minHeight == -1)
					{
						minHeight = table.getRowHeight();
					}
					if (currHeight != passed.length * minHeight)
					{
						currHeight = passed.length * minHeight;
						table.setRowHeight(row, currHeight);
					}
					  
					/*
					 * We create the table that will hold the multivalue fields
					 * and that will be embedded in the main table
					 */
					return new JTable(new AbstractTableModel()
					{
						public int getColumnCount()
						{
							return 1;
						}

						public int getRowCount()
						{
							return passed.length;
						}

						public Object getValueAt(int rowIndex, int columnIndex)
						{
							return passed[rowIndex];
						}

						public boolean isCellEditable(int row, int col)
						{
							return true;
						}
					});
				}
			}
		};
		

		
		
		/* Finally we apply the new cellRenderer to the whole table */
		TableColumnModel tcm = jTableData.getColumnModel();
		for (int it = 0; it < tcm.getColumnCount(); it++)
		{
			tcm.getColumn(it).setCellRenderer(jTableCellRenderer);
		}
		//jTableData.setBackground(Color.cyan);
		//jTableData.setBorder(new EmptyBorder(0,0,0,0));
		/*
		 * Note: if we need to edit the values inside the embedded jtable we
		 * will need to create a TableCellEditor too.
		 */
		add(new JScrollPane(jTableData));
		setSize(400, 400);
		setLocationRelativeTo(null);
	}

	public static void main(String a[])
	{
		new Test1().setVisible(true);
	}
}
 

 

 

swing~转自(http://blog.sina.com.cn/s/blog_4b6047bc010007pd.html

 

Swing框架之Renderer之二

  (2007-01-21 17:11:31)
分类: Swing

   Swing的API具有很强的灵活性和可扩展性,比如标准复合数据型组件一般不需要进行渲染器扩展,就可以实现许多应用,但是当遇到需要自定义扩展的需求时,Swing的高度抽象灵活的MVC框架也可以优雅从容的完成。Swing的这一特色典型的体现在其渲染器扩展思想上。那么如何使用渲染器呢?如何自定义渲染器来扩展组件呢?如何将渲染器思想应用到自定义组件上呢?

   复合数据类型的组件如JTable、JTree、JList以及JComboBox都定义适合自己类型的渲染器接口,它们与渲染器接口之间的映射关系如下表所示:

 组件  渲染器
 JTable  TableCellRenderer
 JTree  TreeCellRenderer
 JList  ListCellRenderer
 JComboBox  ListCellRenderer

   TableCellRenderer接口定义了JTable渲染器接口:

public interface TableCellRenderer {
/*返回渲染表格的组件,使用该方法在渲染之前配置渲染器。
 *参数table:请求渲染器渲染的表,可以为空。
 *参数value:要渲染的单元格的值,由渲染器来决定如何解释和渲染该值。比如如果value的值为字符串“true”,渲染器可以渲染成字符串,也可以渲染成一个check box。该值可以为空。
 *参数isSelected:当前表格是否被选中,渲染器应据此决定是否应该高亮显示。
 *参数hasFocus:当前表格是否拥有焦点,渲染器应据此进行特殊渲染,比如画一个虚线框。
 *参数row:当前表格的行号。如果渲染的是表头,该值为-1。
 *参数column:当前表格的列号。
 */
    Component getTableCellRendererComponent(JTable table, Object value,
         boolean isSelected, boolean hasFocus,
         int row, int column);
}

  TreeCellRenderer定义了JTree的渲染器接口。

public interface TreeCellRenderer {
/*将树当前节点的值赋给value,如果isSelected是true,当前节点要被渲染成选中状态,如果expanded是true,当前节点是处于打开状态,如果leaf是true,当前代表的是一个叶子节点,如果hasFocus是true,表示当前节点拥有焦点。tree是需要渲染的树。改方法返回一渲染组件渲染当前树的节点。*/
    Component getTreeCellRendererComponent(JTree tree, Object value,
       boolean selected, boolean expanded,
       boolean leaf, int row, boolean hasFocus);
}

  ListCellRenderer是JList、JComboBox的渲染器接口。

public interface ListCellRenderer

{
    /* 返回一渲染组件显示列表中的某个选项。参数list是正在渲染的列表,value是列表中当前正在渲染的项,index是当前正在渲染的项的索引,isSelected是当前项是否选中,cellHasFocus是指当前项是否拥有焦点。*/
    Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus);
}

  如何使用这些渲染器接口来实现对这些组件的扩展呢?Jtable中许多方法来实现渲染器的设置,比如方法:

public void setDefaultRenderer(Class columnClass, TableCellRenderer renderer);

  如果在TableColumn中没有设置渲染器的话,该方法设置对于数据类型columnClass应该使用的渲染器。也可以使用
jTable.getColumnModel().getColumn(columnIndex).setCellRenderer(new MyTableCellRenderer())设置columnIndex列的渲染器。最直接的方法是继承JTable,覆盖public TableCellRenderer getCellRenderer(int row, int column) 方法,返回任何位置的TableCellRenderer。该方法使我们能轻易实现类似于NetBeans界面设计工具的属性表:

Swing框架之Renderer之二
  

  在CSDN上有人问如何实现表套表,实际如果清楚了渲染器的工作原理可以很容易实现这个功能,下面是一个很短的代码,它实现了在表的2,3表格中插入一表:

public class TableOfTable extends JTable{
    public TableOfTable() {
        //添加一个缺省model,实际中可以根据自己需求定制。
        setModel(new DefaultTableModel(...... ));
        //将第二行高度设置宽一些,使嵌入的表格显示起来好看些。
        setRowHeight(1,super.getRowHeight()*4);
    }
    //重载getCellRenderer提供自己的TableCellRenderer
    public TableCellRenderer getCellRenderer(int row, int column) {
        if(row == 1 && column==2){//在第二行、第三列提供一个子表的渲染器
            return new TableCellRenderer(){
                //子表,可以自己定制子表的内容。
                JTable subTable=new JTable(new DefaultTableModel(......));
                //实现TableCellRenderer的方法,提供该子表作为渲染器
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                    return subTable;
                }
            };
        }else//如果是其他地方的表格,沿用父类中提供的渲染器
            return super.getCellRenderer(row, column);
    }
}

   短短几行代码就可以实现如下图所示的界面:

Swing框架之Renderer之二
  

   当然你可以根据需求具体定制更为复杂表格的实现,但大体原理就是这样的。

   Jtable、JList、JTree以及JComboBox可以接受的渲染组件不仅仅可以是标准组件,也可以是自定义的组件。比如想实现如下所示的颜色选择器:

Swing框架之Renderer之二
  

  图中的渲染器可以从基本的 BasicComboBoxRenderer 继承,它实际上是继承JLabel的一个类,你可以设置该JLabel的图标,让它显示当前的颜色。为了提供这样一个显示颜色的图标,可以实现这样一个ColorIcon:

public class ColorIcon implements Icon{
static final int BOX=10;
private Color color;
public ColorIcon(Color c){
color=c;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Color old = g.getColor();
g.setColor(color);
g.fillRect(x,y,BOX,BOX);
g.setColor(Color.black);
g.drawRect(x,y,BOX,BOX);
g.setColor(old);
}

public int getIconWidth() {
return BOX;
}

public int getIconHeight() {
return BOX;
}
}

  然后自定义一个渲染器:

public class ColorRenderer extends BasicComboBoxRenderer {
private JComboBox combo;
public ColorRenderer(JComboBox cb) {
combo=cb;
setFont(combo.getFont());
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
JLabel lbl=(JLabel)this;
if(value!=null){
Color c=(Color)value;
lbl.setText(ColorIcon.getColorName(c));
lbl.setIcon(new ColorIcon(c));
}
return this;
}
}

  最后,在程序中使用它:

JcomboBox colorCombo=new JComboBox();
colorCombo.setRenderer(new ColorRenderer(this));
addItem(Color.red);
addItem(Color.orange);
......

  其实,渲染器不仅仅可以用在标准组件JTable、JList、JTree和JComboBox,也可以在自己定制的组件中使用渲染器的思想实现复杂的界面,比如UML图、工作流图、电路图,模拟JTable实现类似于MS Excel的电子表格控件,甚至可以实现自己的用户界面设计工具。前面文章中曾经提到过的数据库设计插件报表设计插件就是根据渲染器原理自定义出的组件。

  因此,熟悉了Swing的结构尤其是渲染器的思想,加上一些额外的知识,比如double buffering、glass pane、robot、swing threading、color model、java2d等等,可以做出许多事情来。人有多大胆,地有多大产。但深入学习和了解Swing的基本结构,这是前提。今天的文章主要是以实例演示了这些渲染器的应用,文中的例子只是演示作用,加深你对渲染器的印象。但是真正吃透渲染器的各种技术,还需要自己深入的学习和实践。 

你可能感兴趣的:(swing,jtable)