Pick Color with JComboBox Java Swing

核能气质少年 提交于 2019-12-05 17:16:57

Try this, should work. You have to override setBackground... because, internal mechanism uses default colors from current Look&Feel:

Color[] colors={Color.white,Color.red,Color.blue,Color.green};
JComboBox colorBox = new JComboBox(colors);
colorBox.setMaximumRowCount(5);
colorBox.setPreferredSize(new Dimension(50,20));
colorBox.setRenderer(new MyCellRenderer());

And ListCellRender:

class MyCellRenderer extends JButton implements ListCellRenderer {  
     public MyCellRenderer() {  
         setOpaque(true); 

     }
     boolean b=false;
    @Override
    public void setBackground(Color bg) {
        // TODO Auto-generated method stub
         if(!b)
         {
             return;
         }

        super.setBackground(bg);
    }
     public Component getListCellRendererComponent(  
         JList list,  
         Object value,  
         int index,  

         boolean isSelected,  
         boolean cellHasFocus)  
     {  

         b=true;
         setText(" ");           
         setBackground((Color)value);        
         b=false;
         return this;  
     }  
}
StanislavL

ComboBox uses equals and all your strings are equal. Define color names

String[] test = {"red", "green" , "blue" ...};

But in the renderer call setText(" ");

Add a case for index == -1 and set the background color of the cell renderer to the most recent user selection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!