设置 JTable 背景 Header 图片

Set JTable Background Header Image

有没有一种简单的方法可以将 JTable header 的背景设置为图像? 我目前有一个 class 扩展 DefaultTableCellRenderer 以更改交替行的格式(和 header 只是作为测试):

public class CustomTable extends DefaultTableCellRenderer{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public CustomTable() {
        super();
        setHorizontalAlignment(JLabel.LEFT);
        setFont(new Font("Apple Casual", 1, 12));

    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean   isSelected, boolean hasFocus, int row, int column) { 
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 

        JTableHeader header = table.getTableHeader();
          header.setBackground(Color.black);
          header.setForeground(Color.yellow);

        if (! table.isRowSelected(row)) {
            if(!((row%2) == 0)) {
                c.setBackground(Color.GRAY);
                c.setForeground(Color.WHITE);
            }
            else {
                c.setBackground(table.getBackground());
                c.setForeground(table.getForeground());
            }
        }
        return c; 
    } 
}

我正在为 JButtons 做类似的事情(如我所愿):

public class CustomButton extends JButton {

     /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Image img;

    public CustomButton(String a){
        super(a);
        try{
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("lightWoodTexture.jpg");
            img = ImageIO.read(inputStream);
            this.setPreferredSize(new Dimension(100,50));
            this.setBackground(new Color(1,1,1, (float) 0.01));
            this.setFont(new Font("Apple Casual", 1, 12));
            this.setForeground(Color.WHITE);
        } catch(IOException e) {
            System.out.println(e.toString());
        }
    }

     @Override
        protected void paintComponent(Graphics g) {
            g.drawImage(img,0,0,null);
            super.paintComponent(g);
        }
}
table.getTableHeader().setDefaultRenderer(new ImageHeaderRenderer());

此代码将您的渲染器设置为 table header。在渲染器中,您可以将图像绘制为 JLabel.

图像单元渲染器:

class ImageHeaderRenderer extends DefaultTableCellRenderer {
  JLabel label = new JLabel();

  ImageIcon icon = new ImageIcon(getClass().getResource("image.png"));

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    label.setText("");
    label.setIcon(icon);
    return label;
  }
}