更改jtable柱头的背景颜色

时间:2012-07-19 19:12:41

标签: java colors jtable

我有一个有四列的表格,我希望每个列头都是不同的颜色。我只希望列头有颜色,而不是列中的其他单元格。我尝试使用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());

3 个答案:

答案 0 :(得分: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));

这应该符合您的需求。

答案 1 :(得分:0)

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

jtable column header with different color

使列标题具有不同的颜色,我有以下3个步骤: 1.在我的项目包中建立一个类。例如,我在其中制作了“ blueHeaderRender.java” 我的项目包。 enter image description here enter image description here

  1. 在您的项目中使用此类。我的GUI项目代码如下:

    private void sqquery1ActionPerformed(java.awt.event.ActionEvent evt){
        //刷新jtable数据     DefaultTableModel模型=(DefaultTableModel)jtps.getModel();     model.setRowCount(0);     DefaultTableModel model02 =(DefaultTableModel)jtsc.getModel();     model02.setRowCount(0);     连接conn = 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) {
        }
    
    }
    

    }

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

答案 2 :(得分:0)

  

上面带有绿色复选标记的代码是正确的,但仅用于设置非标题单元格的属性。请注意,TableColumn类方法setCellRenderer()和setHeaderRenderer()之间有区别。

Resulting table with header cells of multiple colors and non-header yellow cells

/********************* 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();
                    }
                });
            }
        }