⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e933. displaying an icon in a column head of a jtable component.txt

📁 这里面包含了一百多个JAVA源文件
💻 TXT
字号:
Home > List of Packages > javax.swing.table  [62 examples] > Column Heads  [6 examples] 

e933. Displaying an Icon in a Column Head of a JTable Component
Although the default renderer for a table header is a JLabel, the default renderer will only display text. This example demonstrates how to install a custom renderer that can display text as well as icons. 
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    
    // Create 2 columns
    model.addColumn("Col1");
    model.addColumn("Col2");
    // the header value for this column will be overwritten
    // with a TextandIcon object
    
    // Set the icon renderer on the second column
    table.getTableHeader().getColumnModel()
        .getColumn(1).setHeaderRenderer(iconHeaderRenderer);
    
    // Set the text and icon values on the second column for the icon render
    table.getColumnModel().getColumn(1).setHeaderValue(
        new TextAndIcon("Col2", new ImageIcon("icon.gif")));
    
    // This class is used to hold the text and icon values
    // used by the renderer that renders both text and icons
    class TextAndIcon {
        TextAndIcon(String text, Icon icon) {
            this.text = text;
            this.icon = icon;
        }
        String text;
        Icon icon;
    }
    
    // This customized renderer can render objects of the type TextandIcon
    TableCellRenderer iconHeaderRenderer = new DefaultTableCellRenderer() {
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            // Inherit the colors and font from the header component
            if (table != null) {
                JTableHeader header = table.getTableHeader();
                if (header != null) {
                    setForeground(header.getForeground());
                    setBackground(header.getBackground());
                    setFont(header.getFont());
                }
            }
    
            if (value instanceof TextAndIcon) {
                setIcon(((TextAndIcon)value).icon);
                setText(((TextAndIcon)value).text);
            } else {
                setText((value == null) ? "" : value.toString());
                setIcon(null);
            }
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            setHorizontalAlignment(JLabel.CENTER);
            return this;
        }
    };


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -