设置JTable背景标题图像

时间:2016-03-18 13:04:24

标签: java swing jtable tablecellrenderer jtableheader

是否有一种简单的方法可以将JTable标题的背景设置为图像? 我目前有一个扩展DefaultTableCellRenderer的类来更改备用行的格式(以及标题作为测试):

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

1 个答案:

答案 0 :(得分:0)

table.getTableHeader().setDefaultRenderer(new ImageHeaderRenderer());

此代码将渲染器设置为表头。在渲染器中,您可以将图像绘制为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;
  }
}