Custom ListCellRenderer will not change background color

前端 未结 3 802
挽巷
挽巷 2021-01-06 05:22

I have this class:

 @SuppressWarnings(\"serial\")
  private class DataCellRenderer extends JLabel implements ListCellRenderer 
  {
    public DataCellRender         


        
3条回答
  •  一个人的身影
    2021-01-06 05:25

    The main problem is that labels are non-opaque by default, so you need to make the label opaque in order for the background to be painted.

    But you don't need to create a custom renderer for this. The default renderer is opaque. All you need to do is set the selection background property of the list:

    list.setSelectionBackground(Color.RED);
    

    If you are trying to create a renderer to right align the text then you can just set a property on the default renderer:

    DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.RIGHT);
    

提交回复
热议问题