首页 > 其他 > 详细

设计一个特殊表格的JTable控件

时间:2021-02-02 22:05:04      阅读:28      评论:0      收藏:0      [点我收藏+]
public class MutilHeadTable extends JTable {

	public MutilHeadTable(TableModel tm) {
		super(tm);
		init();
	}
	
	private void init(){
		//为每个列添加自定义的RENDER.这个Api设计比较麻烦.
		CustomizedHeaderRender r = new CustomizedHeaderRender();
		for (int i=0; i< getModel().getColumnCount(); i++) {
			 TableColumn column = getColumnModel().getColumn(i);
			 column.setHeaderRenderer(new CustomizedHeaderRender());
		}
	}
	private class CustomizedHeaderRender extends DefaultTableCellRenderer{
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
                int column) {
			 if(value!=null && value instanceof String){
				 StringTokenizer t = new StringTokenizer((String)value,"/");
				 StringBuffer bf = new StringBuffer();
				 bf.append("<html>");
				 while (t.hasMoreElements()){
					 bf.append(t.nextElement());
					 if(t.hasMoreElements()){
						 bf.append("<br>");
					 }else{
						  bf.append("</html>");
					 }
				 }
				 return new JLabel(bf.toString());
			 }
			 return this;
		}
	}
	
	public static void main(String[] args) {
		JFrame frame = new JFrame("Leaders");
		Container contentPane = frame.getContentPane();
		String headers[] = {"Line1/line2/line3", "Country"};
		String data[][] = {
				{"Tony Blair", "England"},
				{"Thabo Mbeki", "South Africa"},
		};
		TableModel model = new DefaultTableModel(data, headers);
		MutilHeadTable table = new MutilHeadTable(model);
		JScrollPane scrollPane = new JScrollPane (table);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		frame.setSize(300, 100);
		frame.setVisible(true);
	}
}

  效果图:

技术分享图片

 

设计一个特殊表格的JTable控件

原文:https://www.cnblogs.com/wwssgg/p/14364225.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!