How to set the color of a Font?

时光总嘲笑我的痴心妄想 提交于 2019-12-08 02:41:26

问题


I have a JList and inside that list, I want to change the color of the font of the following words.

Someone said that I have to use CellRenderer but I'm not yet familiar with that.

Now, my problem is how can I setup this renderer to change the color of the Font?

Any idea about this matter?

Thanks...


回答1:


Check out the JavaDoc, it might just have what you need (the example at the top). Basically you just return a component (like a JLabel) with a configured font color.

Edit: since you want to have the words in a different color than their definitions, here two possibilities how that can be done with the list cell renderer:

  1. Return a JPanel that contains 2 JLabels, one with the word and one with the definitions. Both labels can have different foreground colors.
  2. JLabel supports HTML (like other Swing components do), so you might just set the text of the label as <html><font color=red>your word</font> - your definitions</html>. Note that the default foreground color should then be the one for the definitions, alternatively you can wrap the definitions with a <font> tag as well. Have a look at this Tutorial.



回答2:


For JLabel components try:

    new DefaultListCellRenderer(){
        @Override
        public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) { 
            JLabel label = (JLabel)super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus );
            label.setForeground( Color.RED );
            return label;
        }  
    };



回答3:


consider ...., that would be better using a JTable with one TableColumn and without TableHeader as the JList, demonstrated here, here, by using prepareRenderer, because JList has lots of restriction/missed methods as JTable



来源:https://stackoverflow.com/questions/7331388/how-to-set-the-color-of-a-font

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