質問

I want to align the contents of the first column of my JTable to the center, but I can't get it to work. I got it to work if I set it without a custom Renderer but then it would overwrite the changes I'm trying to make for the row colors.

Eclipse tells me that the method setHorizontalAlignment is undefined for the type Component but that doesn't ring any bells with me. Any ideas what I'm missing?

final TableCellRenderer renderer = table_1.getDefaultRenderer(Object.class);
    table_1.setDefaultRenderer(Object.class, new TableCellRenderer()    {
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) 
      {
        Component c = renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 4 == 2 || row % 4 == 3 ? new Color(230,230,230) : Color.WHITE);
        c.setHorizontalAlignment(JLabel.CENTER);
        return c;
      }
    }); 
役に立ちましたか?

解決

Declare and cast the variable c to JLabel:

JLabel c = (JLabel) renderer.getTableCellRendererComponent(...);

The API for DefaultTableCellRenderer will show you that this class in fact derives from JLabel which has the method that you're interested in.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top