Diferent font in JList

hi is there a way to make each element in a JList to a different font. i am making a FontDialog and i would like each font name in the list to be the font of that font... like in MS word.
many thanks
David

Use a customized ListCellRenderer. The following outlines one possible way of doing it:
    // Use instances of this class as items in your list:
    class FontListItem {
        private Font    font;
        public FontListItem(Font font) {
            this.font = font;
        public String toString() {
            return font.getName();
        public Font getFont() {
            return font;
    // The ListCellRenderer for your JList:
    class FontListRenderer extends DefaultListCellRenderer {
        public Component getListCellRendererComponent(JList list,
                                                      Object value,
                                                      int index,
                                                      boolean isSelected,
                                                      boolean cellHasFocus) {
            JLabel renderer = (JLabel)super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);
            if( value instanceof FontListItem ) {
                renderer.setFont( ((FontListItem)value).getFont() );
            return renderer;
    // Example of use:
    FontListItem[] listItems = ...
    JList list = new JList(listItems);
    list.setCellRenderer(new FontListRenderer());

Similar Messages

  • Images and fonts in JList

    How to add icon to JList? But I need to add icon in spacial way (so common metho of changing of cellRenderer don`t help) I need to add icons at two places, at the beginging of word and at the end of word (aligned to right border).
    Also how to change font of one of elements, for example I need to add red bold text.

    here is an example hope that it helps you...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    *This is a class that can genernate the font dialog and returns the font
    *@author David Rubin
    *@version 1.2  15 july 2005
    public class FontDialog extends JDialog
        private static final String FONT_NAMES [] = GraphicsEnvironment.getLocalGraphicsEnvironment ().getAvailableFontFamilyNames ();
        private Font returnFont = null;
        private DefaultListModel fontModel = new DefaultListModel ();
        private JList fontNames;
        private SpinnerNumberModel spinModel = new SpinnerNumberModel (12, 1, 150, 1);
        private JSpinner fontSizes = new JSpinner (spinModel);
        private JCheckBox bold = new JCheckBox ("Bold");
        private JCheckBox italic = new JCheckBox ("Italic");
        private JTextField canvas = new JTextField ("aB cb gG xX yY zZ the old man");
        private int prop = 0;
        public FontDialog (JFrame parent)
       super (parent, "Font Dialog", true);
       ((JSpinner.DefaultEditor) fontSizes.getEditor ()).getTextField ()
              .addKeyListener (new KeyAdapter ()
           public void keyTyped (KeyEvent e)
          if (!Character.isDigit (e.getKeyChar ()))
              e.consume ();
       fontSizes.addChangeListener (new ChangeListener ()
           public void stateChanged (ChangeEvent e)
          canvas.setFont (new Font ((String) fontNames.getSelectedValue (), prop, ((Integer) fontSizes.getValue ()).intValue ()));
       fontNames = new JList (fontModel);
       fontNames.addListSelectionListener (new ListSelectionListener ()
           public void valueChanged (ListSelectionEvent e)
          canvas.setFont (new Font ((String) fontNames.getSelectedValue (), prop, ((Integer) fontSizes.getValue ()).intValue ()));
       for (int i = 0 ; i < FONT_NAMES.length ; i++)
           fontModel.addElement (FONT_NAMES );
    fontNames.setCellRenderer (new MyCellRenderer ());
    JScrollPane scrolPane = new JScrollPane (fontNames);
    this.getContentPane ().add (scrolPane, BorderLayout.WEST);
    ActionListener act = new ActionListener ()
    public void actionPerformed (ActionEvent e)
    if (e.getSource () == bold)
    prop ^= Font.BOLD;
    else if (e.getSource () == italic)
    prop ^= Font.ITALIC;
    canvas.setFont (new Font ((String) fontNames.getSelectedValue (), prop, ((Integer) fontSizes.getValue ()).intValue ()));
    ActionListener actList = new ActionListener ()
    public void actionPerformed (ActionEvent e)
    Font t = canvas.getFont ();
    String s;
    if (t.isBold () && t.isItalic ())
    s = "Font.BOLD|Font.ITALIC";
    else if (t.isBold ())
    s = "Font.BOLD";
    else if (t.isItalic ())
    s = "Font.ITALIC";
    else
    s = "Font.PLAIN";
    System.out.println ("Font f=new Font(\"" + t.getFontName () + "\"," + s + "," + t.getSize () + ");");
    JPanel pan = new JPanel ();
    bold.addActionListener (act);
    italic.addActionListener (act);
    pan.add (bold);
    pan.add (italic);
    pan.add (fontSizes);
    pan.setBorder (BorderFactory.createTitledBorder ("Options"));
    JPanel pan1 = new JPanel ();
    pan1.add (pan);
    JButton but = new JButton ("Print Font ");
    but.addActionListener (actList);
    pan1.add (but);
    canvas.setMinimumSize (new Dimension (50, 60));
    canvas.setPreferredSize (new Dimension (50, 60));
    this.getContentPane ().add (pan1, BorderLayout.EAST);
    this.getContentPane ().add (canvas, BorderLayout.SOUTH);
    pack ();
    this.setVisible (true);
    class MyCellRenderer extends JLabel implements ListCellRenderer
    public Component getListCellRendererComponent (JList list, Object value,
    int index, boolean isSelected, boolean cellHasFocus)
    String s = value.toString ();
    setText (s);
    if (isSelected)
    this.setBackground (list.getSelectionBackground ());
    this.setForeground (list.getSelectionForeground ());
    else
    this.setBackground (list.getBackground ());
    this.setForeground (list.getForeground ());
    this.setEnabled (list.isEnabled ());
    this.setFont (new Font (s, Font.PLAIN, 13));
    setOpaque (true);
    return this;
    public Font getFont ()
    return canvas.getFont ();
    public static void main (String [] args)
    FontDialog fontdialog = new FontDialog (null);

  • Getting differend fonts on JList

    I was helped to do like this to get different fonts visible on JList. How ever I can't get selectable list (Jlist) of fonts shows on it's own font...
    If i create a Component and FontListCellRenderer and use FontListCellREnderers method getCellListRendererComponent(.....) I can place the return value into this new Component and add this component to JPanel...
    but how to do this so that all the fonts are shown in a list and the list added to JPanel?
    String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    Font[] fonts = new Font[fontNames.length];
    for(int idx = 0; idx < fontNames.length; idx++)
              fonts[idx] = new Font(fontNames[idx], Font.PLAIN, 12);
    JList fontList = new JList(fonts);
    fontList.setCellRenderer(new FontListCellRenderer());          
    public class FontListCellRenderer extends DefaultListCellRenderer
    public Component getListCellRendererComponent(JList list, Object value, int idx, boolean isSelected, boolean hasFocus)
    // Assume that the list is populated with Fonts...
    Font font = (Font)value;
    // Get a renderer component suitable for displaying the name of the font
    Component comp = super.getListCellRendererComponent(list, font.getName(), idx, isSelected, hasFocus);
    // Alter the renderer component to use the font
    comp.setFont(font);
    return comp;
    P_trig     

    This would not take care of all issues but have you tried changing Preferences – Interface – UI Font Size?

  • Diferent font format for Parent/Child

    Hello,With Excel Add-In, we can format the letter font differently for parent and child, using the Essbase Option (Style -> Members -> Parent -> Format).How can we do, the same thing, using Analyzer.Any help is appreciated.SL

    Hi,Unfortunately there are no advanced formatting options in the current release of Analyzer (6.2.1). You can either format the data or the metadata (headers). I believe in the next release there are plans to incorporate more formatting options.Hope this helps.Paul ArmitageAnalitica Ltdwww.analitica.co.uk

  • Set diferent font in a paragraph text.

    In xml file,there is the following element:
    When I open the xml file in FrameMaker,the font of string "ZCCC2.1" should Times new roman,the font of string "ADCCCCCCCC" should another font.
    In EDD,title element is a framemaker element.How Can I deal with the problem when I open the xml file?

    Bummer! Thanks for letting me know, so I can stop banging my head against the wall trying to figure it out.
    Your approach with the dummy font is clever, but won't help me in this case. I'm trying to automate the "Find Font" process for a group of users. They've used a particular group of fonts for thousands of files, and are switching to a different family of fonts. They want to have ONLY the new family installed. So I wanted to create a script they could run the first time they open each file that would find each old font and replace it with the new font. My script works great for all the text in the file, but not the Paragraph and Character styles.
    Can anyone think of another approach? I'm out of ideas on this one.

  • Using diferent font sizes in a tree componnet

    Hello,
    I need help custumizing my tree component.
    I've spended my last 3 days searching for a solution to have
    my branches using fontsize = 16 and their childs using fontsize =
    12.
    Do you have any idea on how to achieve this?
    I've tryed many things in the tree.as, list.as, treeRow.as
    classes, but I can't figure how to manage this.
    Thanks a lot for help,

    hi,
    i think "setPropertiesAt" may help you.
    look this code.
    var my_list:mx.controls.List;
    my_list.setSize(200, 100);
    my_list.addItem({data:"flash", label:"Flash"});
    my_list.addItem({data:"dreamweaver", label:"Dreamweaver"});
    my_list.addItem({data:"coldfusion", label:"ColdFusion"});
    my_list.setPropertiesAt(2, {backgroundColor:0xFF0000, icon:
    "file"});
    But, i am not sure pluda.

  • Knowledge Management and Message functionality

    Hi all,
    i'm looking to develop a solution to provide following functionality
    message capabilities  we would like to have especific messages for R/3 BW or CRM users also we would like to be able to create  messages would be outage messages this messages has the ability to disable connection with backend systems between two dates and display a adverstiment of this some time before
    this messages must be visible only for some users base on the team/ roles they have
    I never work with KM before and i have some doubts
    we would like to know if KM is the right place to store this messages
    KM has some templates to post messages with especific structure
    can we separate messages base on roles or groups?
    this messages has edit functionalities like WYSIWYG editor create messages with Links, bold italic or colors and diferent fonts
    also any help about API to manage KM will be great
    thanks for your help
    any input will be apreciate and rewarded
    best regards

    Hi Ruben,
    About your doubts,
    we would like to know if KM is the right place to store this messages
    Yes, you can store messages in KM. It is the better place.
    KM has some templates to post messages with especific structure
    Not sure about this. But, You can have metadata property of type HTML. You can create specific stuctures here.
    can we separate messages base on roles or groups?
    Yes, Definately.
    this messages has edit functionalities like WYSIWYG editor create messages with Links, bold italic or colors and diferent fonts
    Yes, While creating messages manually in KM, the tool bar is available for editing such things.
    For API's you can refer help.sap.com.
    Thanks,
    Mehul
    Reward points if answer is helpful.

  • How to specify the font in a JList?

    My application has four columns of data represented in a JList. The default font style does proportional spacing.
    I need to specify a fixed width font to control column alignment in the JList. Unless there's something like tab positions? If I can specify a fixed width font, I can format the display strings appropriately.
    I think I need to use a cell renderer to control the actual drawing of each cell in the JList?
    Also, where do I find a list of the font types?
    Thanks in advance!

    I don't think you need a cell renderer. You find out how to specify font names by (oddly enough) looking in the API documentation for the Font class; the info for the most usable-looking constructor tells you what you want to know.

  • Difference in font rendering of JList and other text components

    Hi,
    I have a swing application using JTextField,JTextArea and JList.When I use a font
    for an Indian Language for these components,the JList shows the data correctly
    but the other components shows it with junk characters.Is there a difference in the font rendering behaviour of JList from others?

    Use getFont() on each to the comonents to make sure they are using the same font.

  • Changing JList non-editable Font color of the selected items

    Hi All,
    I want to change the font color of non-editable JList's selected items which is not clearly visible to user. And I need to change the font color only the selected item in this scenerio.
    Could you please clarify me?
    <img src="file:///C:/DOCUME~1/sgnanasi/LOCALS~1/Temp/moz-screenshot-4.png" alt="" />

    [email protected] wrote:
    ..I want to change the font color of non-editable JList's selected items which is not clearly visible to user. And I need to change the font color only the selected item in this scenerio.Set a custom [cell renderer|http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html] *(<- link)* for the JList.

  • Printing JList - font problems

    i am using a class that takes a Component and prints it.
    in windows:
    when i send a JList, it prints using the standard java font. if i set the LookAndFeel to the DefaultOS, then if i set font that is what I am assuming to be the System default (in windows this seems to be "sansserrif" size 11).
    in mac os:
    when i try to print the JList it spits out a different font and much larger font size, so it's throwing off my usable print area. i tried setting the font of the JList to the "sansserrif" but it had no effect....it's still printing using the default mac font. i had my gui show me the jlist...it looks identical to how it looked in windows....until i print. method used: jList.setFont(new Font("sansserif", Font.PLAIN, 11));how do i override this with my own font? and why would it let me override it in windows? seems fishy to me... (i hope i was somewhat clear...i think im confusing even myself at this point)

    in case anyone was interested...i was able to get cross-platform printing to work "good enough." although not identical, these two variations produced nearly the same result (the only difference was that the cell heights weren't quite the same... i think 10.5 for the mac version would match 14 for windows perfectly, but only integers are accepted as parameters for the setFixedCellHeight() method).
    i also had to fix the print graphics translation to set a 1" top, left margin in stone...the mac os wanted the margin to be just a fraction of an inch.
    //for 8.5" x 11" pages:
    jList = new JList(theModel);
        jList.setLayoutOrientation(JList.VERTICAL_WRAP);
        jList.setVisibleRowCount(-1);
        if (windows)
          jList.setFont(new Font("sansserif", Font.PLAIN, 11));
          jList.setPreferredSize(new Dimension(620,860));
          jList.setFixedCellHeight(14);
          jList.setFixedCellWidth(210);
        else //mac
          jList.setFont(new Font("sansserif", Font.PLAIN, 8));
          jList.setSize(new Dimension(470,673));
          jList.setFixedCellHeight(11);
          jList.setFixedCellWidth(155);
        }again, this was sending a 3-column JList as a component to a printing function.

  • JList with items having different fonts

    Hi,
    Does anyone know how I can create a list of items, and have some of them shown in bold?
    JList only uses the one font for all its items.
    Regards,
    Paul

    To pass font info to the renderer you have 2 choises:
    1) extend JList, so that your one has some property defining the font (based on the index) and a render using it (like a Vector<Font>)
    2) put objects of a specific complex type in the list, each containing the label and the font; having the render (extending the default one) like +if (instanceof myType){ ... } else return super.getListCellComponent...+ (or whatever the name of the method, I don't remember)
    One last thing: defaultRenderer returns JLabels so you can use html in it. I guess you can use default renderer populating list with strings like +<html><font ..>value+. This only works fine if the index is self-explanatory in your logic, otherwise losing logic, plus the effort to 'extract' the actual info from formatted html value, aren't worth having not to write a very simple renderer.
    Bye.

  • Diferent Window Managers/Desktop Managers diferente font sizes.

    For some time now I've used openbox.... and i like it very alot.
    But along came AIGLX and Beryl  :D:D:D
    I had to try it!!!!
    So I installed gnome and am currently using it (with and without Beryl)
    But I noticed something strange:the font sizes where completely different from OpenBox.
    The fonts I used for the applications in  Openbox "grew" when I started them in Gnome.
    If I set the fonts I like in gnome, then they "shrink" when run in OpenBox......
    This is a small problem (not really important) but it's been bugging me for some days now...... and I just want to know why this happens and (if possible) how to fix it.

    rufus wrote:can you post yur .bashrc pleez
    its just the default one, that doesn't do anything, except I added a startx, to make booting more convenient.
    Edit: I know it doesn't do nothing, but nothing relating to this issue.
    # ~/.bashrc
    # If not running interactively, don't do anything
    [[ $- != *i* ]] && return
    alias ls='ls --color=auto'
    PS1='[\u@\h \W]\$ '
    startx
    Last edited by rh995 (2013-08-23 05:17:30)

  • Generate PDF with Draft font

    Hi,
    I'm generating a report in Oracle with DRAFT 10 CPI font but when I check the PDF file font is diferent, how can I correct this?, Where can I find the DRAFT 10 CPI font ?

    As long as the font is on your system and it is licensed for embedding, you need to embed the font in the PDF. That is set within the job.options. Typically the print and press job options will embed all fonts. Standard will embed most. Smallest-file-size embeds no fonts as I recall.

  • How to get default color of a selected row in a JLIst

    I have a JList that I am changing the font color for based on a certian situation so I created my own MyCellRenderer to do this. However, when I select an item in the list the row is no longer highlighted. I used the isSelected method to determine if a row was selected and then change the background color of that row. However, I would like the color to be the default color that you get when you select a row in a default JList. I can't seem to figure out how to get that color. How do I obtain what that color is? I found an example where you can get the default color for the background of a button and use that color so I would guess it is something similar to that. My code is below so I hope someone can tell me how to get that color that I want.
    Thanks...Chris
    class MyCellRenderer extends JLabel implements ListCellRenderer {
         public MyCellRenderer() {
              setOpaque(true);
         public Component getListCellRendererComponent(
             JList list,
             Object value,
             int index,
             boolean isSelected,
             boolean cellHasFocus)
             int index1 = value.toString().indexOf("-");
               String errors = value.toString().substring(index1 + 1, index1 + 6).trim();
             int numErrors = Integer.parseInt(errors);
               if (numErrors > 0)
                      setForeground(Color.red);
                      setBackground(Color.white);          
             else
                  setBackground(Color.white);
                  setForeground(Color.black);
             if(isSelected)
                  //ColorUIResource col = (ColorUIResource)UIManager.getDefaults().get("JButton.background");
                  ColorUIResource col = (ColorUIResource)UIManager.getDefaults().get("Button.background");
                  setBackground(col);
             setText(value.toString());
             return this;
    }

    Swing related questions should be posted in the Swing forum.
    I would like the color to be the default color that you get when you select a row in a default JList. I can't seem to figure out how to get that colorlist.getSelectionBackground();

Maybe you are looking for

  • Send error report? No! I just want my music!

    "iTunes has encountered a problem and needs to close. We are sorry for the inconvenience." Every time i click on iTunes it asks me if i want to send an error report. I doesn't even tell me what type of error it's having.I tried reinstalling iTunes an

  • Unable to provision Business Rules access for users

    Hi all, Our analytic server is properly configured in Shared Services : we can correctly create users, provision Essbase access for those users, change password, etc... An application business rules is visible in the left pane of shared services, but

  • The maximum length of java.lang.String

    Currently I working for intrepret an XML file and transform to another XML using XSLT based on the the DOM node reading concept. I have a study that i need to input a String type of the XML file content, and the maximum size of the String is possibly

  • Combobox Autocomplete editor inside Jtable cell

    I have a custom combobox editor which supports the autocomplete feature as follows: as soon as the user keys in any character, this editor searches for the item that starts with keyed in character. This item is displayed in the editor text field and

  • Profit center assignment to material

    Hi! I have divided my profit center hierarchy in such a way - that I could easily prepare a COS profit and loss statement using them. Basically I have such profit centers like: - Profit on sale of Goods - Profit on sale of Materials - Profit on sale