码迷,mamicode.com
首页 > 编程语言 > 详细

实现Java JTable的应用案例

时间:2014-11-17 10:36:29      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   java   for   div   on   

代码如下

import Java.awt.Component;   
import java.awt.Dimension;   
import java.awt.FontMetrics;   
  
import javax.swing.JLabel;   
import javax.swing.JTable;   
import javax.swing.UIManager;   
import javax.swing.table.DefaultTableCellRenderer;   
import javax.swing.table.JTableHeader;   
import javax.swing.table.TableColumnModel;   
  
public class Main extends DefaultTableCellRenderer {   
        private static final long serialVersionUID = 1L;

        public Component getTableCellRendererComponent(JTable table, Object value,   
            boolean isSelected, boolean hasFocus, int row, int column) {   
  
        JTableHeader header = table.getTableHeader();   
        setForeground(header.getForeground());   
        setBackground(header.getBackground());   
        setFont(header.getFont());   
        setOpaque(true);   
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));   
  
        // 得到列的宽度   
        TableColumnModel columnModel = table.getColumnModel();   
        int width = columnModel.getColumn(column).getWidth();   
  
        value = getShowValue(value.toString(), width);   
        setText(value.toString());   
        setSize(new Dimension(width, this.getHeight()));   
  
        setHorizontalAlignment(JLabel.CENTER);   
  
        return this;   
    }   
  
    private Object getShowValue(String value, int colWidth) {   
        FontMetrics fm = this.getFontMetrics(this.getFont());   
        int width = fm.stringWidth(value.toString());   
        int test = fm.stringWidth("好");   
        System.out.println(test * value.length());   
        System.out.println(width);   
        if (width < colWidth) {   
            return value;   
        }   
        StringBuffer sb = new StringBuffer("<html>");   
        char str;   
        int tempW = 0;   
        for (int i = 0; i < value.length(); i++) {   
            str = value.charAt(i);   
            tempW += fm.charWidth(str);   
            if (tempW > colWidth) {   
                sb.append("<br>");   
                tempW = 0;   
            }   
            sb.append(str);   
        }   
        sb.append("</html>");   
        return sb.toString();   
    }   
}

  运行结果
<ignore_js_op>bubuko.com,布布扣

详细说明:http://java.662p.com/thread-3683-1-1.html

实现Java JTable的应用案例

标签:blog   http   io   ar   os   java   for   div   on   

原文地址:http://www.cnblogs.com/huasili/p/4102938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!