Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Change the font in a JList

 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am unable to change the font of the items in the JList. Is there a way to do it?

Thanks.
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vani Shastri:
Hi,

I am unable to change the font of the items in the JList. Is there a way to do it?

Thanks.


Dear Vani,

Are you interested to change the font for each item present in JList or you simple want to change the font for all items in JList....

 
Anand Loni
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vani,

If you want to set same font for each item then you can simply set font for the list using,

list.setFont(new Font("Arial",Font.BOLD,14));

I have used Font Name as Arial here you can use others.
If you want to change font of particular item from list you have change this in renderer of that list.
As renderer for list uses JLabel as each item you can explicitly set font for that label.

Regards,
Anand
 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Ankur and Anand.
But there is another doubt. I want to change the font of just one particular item in the JList. Is it possible?
 
Anand Loni
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As I have told already in previous reply, you can change font of particular item of the list in renderer. Sample code would be

class MyListCellRenderer extends DefaultListCellRenderer
{

JLabel label;
Font font;
MyListCellRenderer()
{
font = new Font("Areal", Font.BOLD,14);
}
public Component getListCellRendererComponent(JList list, // The list
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the focus
{
label = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
if(//condition to select particular label whose font to be set)
{
label.setFont(font) ;
}
else
{
label.setFont(list.getFont());
}

}
}

Hope this helps..
 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Anand
Have a nice day
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic