0

我有一个有四列的表格,我希望每个列的标题都是不同的颜色。我只希望列头有颜色,而不是列中的其余单元格。我尝试使用 DefaultTableCellRenderer,但它使除列标题之外的每个单元格都变成红色。我可以在我的代码(如下)中进行哪些更改以单独为每个列标题分配颜色?

class CustomRenderer extends DefaultTableCellRenderer{

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, 3, 3);
    c.setBackground(new java.awt.Color(255,72,72));
    return c;
}

}

    table.setDefaultRenderer(Object.class, new CustomRenderer());
4

3 回答 3

1

恐怕您无法轻松设置每种颜色。

// Get the column header for your specific column
JTableHeader th = table.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
TableColumn tc = tcm.getColumn(column);

/* Create a new renderer for column headers, and
pass in the column number so you can differntiate
which column will be which color. */
tc.setCellRenderer(new headerCellRenderer(column));

不过,这应该适合您的需求。

于 2012-07-19T19:26:54.497 回答
0

下面是我在 Netbeans GUI 项目中的解决方案:

不同颜色的jtable列标题

制作不同颜色的列标题,我有以下 3 个步骤: 1.在我的项目包中构建一个类。例如,我在我的项目包中制作了“blueHeaderRender.java”。 在此处输入图像描述 在此处输入图像描述

  1. 在你的项目中使用这个类。我的GUI项目代码如下:

    private void sqquery1ActionPerformed(java.awt.event.ActionEvent evt) {
    //刷新jtable数据 DefaultTableModel model = (DefaultTableModel) jtps.getModel(); 模型.setRowCount(0); DefaultTableModel model02 = (DefaultTableModel) jtsc.getModel(); model02.setRowCount(0); 连接连接 = getConnection(); 字符串 date1=getdate01.getText(); 字符串 date2=getdate02.getText(); DateFormat df=new SimpleDateFormat("yyyy-MM-dd"); if(jDateChooser1.getDate()!=null&jDateChooser2.getDate()!=null){ getdate01.setText(df.format(jDateChooser1.getDate())); getdate02.setText(df.format(jDateChooser2.getDate())); } 其他{ getdate01.setText(""); getdate02.setText(""); }

    if(!"".equals(getdate01.getText())&!"".equals(getdate02.getText())){
        String query001 =" SELECT * FROM pscard_in_out WHERE CAST(datetime AS date) BETWEEN '"+getdate01.getText()+"' AND '"+getdate02.getText()+"'  ";
    
        String query002 =" SELECT * FROM sccard_in_out WHERE CAST(datetime AS date) BETWEEN '"+getdate01.getText()+"' AND '"+getdate02.getText()+"'  ";
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(query001);
            rs = pstmt.executeQuery();
    
            jtps.setModel(DbUtils.resultSetToTableModel(rs));  //neen import rs2xml.jar  in libraries
            jtps.getColumnModel().getColumn(2).setHeaderRenderer(new blueHeaderRenderer());
            jtps.getColumnModel().getColumn(4).setHeaderRenderer(new blueHeaderRenderer());
            jtps.getColumnModel().getColumn(3).setHeaderRenderer(new redHeaderRenderer());
            jtps.getColumnModel().getColumn(5).setHeaderRenderer(new redHeaderRenderer());
            // resizing the column width
            jtps.getColumnModel().getColumn(0).setPreferredWidth(40);
            jtps.getColumnModel().getColumn(1).setPreferredWidth(190);
            jtps.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    
            while (rs.next()){}
    
            pscardSum();
            pstmt.close();
            rs.close();
            conn.close();
    
        } catch (SQLException ex) {
        }
    
    }
    

    }

顺便说一句,如果你想在不同的列标题中使用另一种颜色,你可以在你的项目中制作更多的类以在你的项目中使用。

于 2019-09-26T10:50:20.510 回答
0

上面标有绿色复选标记的代码是正确的,但只是设置了非标题单元格的属性。请注意,TableColumn 类方法 setCellRenderer() 和 setHeaderRenderer() 之间存在差异。

具有多种颜色的标题单元格和非标题黄色单元格的结果表

/********************* FULL WORKING IMPLEMENTATION. *************************
  -Table with custom header (multiple colors) and custom non-header cells.
  -Cells' manipulated properties are colors, font, opacity and border types.*/

        import java.awt.Color;
        import java.awt.Component;
        import java.awt.Dimension;
        import java.awt.Font;
        import java.awt.GridLayout;
        import javax.swing.BorderFactory;
        import javax.swing.JComponent;
        import javax.swing.JFrame;
        import javax.swing.JLabel;
        import javax.swing.JPanel;
        import javax.swing.JScrollPane;
        import javax.swing.JTable;
        import javax.swing.border.Border;
        import javax.swing.table.AbstractTableModel;
        import javax.swing.table.TableCellRenderer;
        import javax.swing.table.TableColumn;

        public class CustomHeaderTable  extends JPanel
        {
            CustomHeaderTable()
            {
                super(new GridLayout(1,0));

                JTable table = new JTable(new MyTableModel());
                table.setPreferredScrollableViewportSize(table.getPreferredSize());
                table.setFillsViewportHeight(true);
                table.setPreferredScrollableViewportSize(new Dimension(500, 70));

                //Setting header cells
                CustomCellRenderer customHeaderCellRenderer = 
                        new CustomCellRenderer(Color.white,
                                               Color.red,
                                               new Font("Consolas",Font.BOLD,14),
                                               BorderFactory.createEtchedBorder(),
                                               true);

                for(int columnIndex = 0; columnIndex < table.getTableHeader().getColumnModel().getColumnCount(); columnIndex++)
                {
                    TableColumn tc = table.getTableHeader().getColumnModel().getColumn(columnIndex);    
                    tc.setHeaderRenderer(customHeaderCellRenderer);
                }

                //Setting non-heather's cells colors, font, borders, and opacity
                CustomCellRenderer customNonHeaderCellRenderer = 
                        new CustomCellRenderer(Color.blue,
                                               Color.yellow,
                                               new Font("Courier",Font.PLAIN,12),
                                               BorderFactory.createLineBorder(Color.gray),
                                               true);

                for(int columnIndex = 0; columnIndex < table.getTableHeader().getColumnModel().getColumnCount(); columnIndex++)
                {
                    TableColumn tc = table.getTableHeader().getColumnModel().getColumn(columnIndex);    
                    tc.setCellRenderer(customNonHeaderCellRenderer);
                }

                JScrollPane scrollpane = new JScrollPane(table);
                add(scrollpane);
            }

            public class CustomCellRenderer extends JLabel implements TableCellRenderer
            {
                public CustomCellRenderer(Color foregroundColor, Color backgroundColor, Font font, Border border, boolean isOpaque)
                {
                    setFont(font);
                    setOpaque(isOpaque);
                    setForeground(foregroundColor);
                    setBackground(backgroundColor);
                    setBorder(border); 
                }

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) 
                {
                    setText(value.toString());
                    return this;
                }
            }

            class MyTableModel extends AbstractTableModel 
            {
                private String[] columnNames = {"First Name",
                                                "Last Name",
                                                "Sport",
                                                "# of Years",`enter code here`
                                                "Vegetarian"};
                private Object[][] data = {
                {"Kathy", "Smith",
                 "Snowboarding", new Integer(5), false},
                {"John", "Doe",
                 "Rowing", new Integer(3), true},
                {"Sue", "Black",
                 "Knitting", new Integer(2), false},
                {"Jane", "White",
                 "Speed reading", new Integer(20), true},
                {"Joe", "Brown",
                 "Pool", new Integer(10), false}
                };

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

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

                public String getColumnName(int col) 
                {
                    return columnNames[col];
                }

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

                public Class getColumnClass(int c) 
                {
                    return getValueAt(0, c).getClass();
                }

                public boolean isCellEditable(int row, int col) 
                {
                    if (col < 3) 
                    {
                        return false;
                    } 
                    else 
                    {
                        return true;
                    }
                }
            }

            public static void createAndShowGUI()
            {
                JFrame frame = new JFrame("CustomHeaderTable");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JComponent newContentPane = new CustomHeaderTable();
                newContentPane.setOpaque(true);
                frame.setContentPane(newContentPane);

                frame.pack();
                frame.setLocationRelativeTo( null );
                frame.setVisible(true);
            }

            public static void main(String[] args) {
                javax.swing.SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        createAndShowGUI();
                    }
                });
            }
        }
于 2019-10-22T03:35:46.597 回答