这里面包含了一百多个JAVA源文件

源代码在线查看: e933. displaying an icon in a column head of a jtable component.txt

软件大小: 551 K
上传用户: maple_78
关键词: JAVA
下载地址: 免注册下载 普通下载 VIP

相关代码

				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;
				        }
				    };
				
				
							

相关资源