Rendering JList items instantly

hi friends
I wanna know how to rendering JList items instantly without selecting any item,so the rendering of the item has to be automatically.
thank you very much

Well how does the icon change? Normally changes to the data are done by updating the model, in which case the list will get painted automatically.
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

Similar Messages

  • How to center JList  items

    Hi,
    I want to center my Jlist item instead of leave them in the left like usual. My List contains pictures and for the beauty of the design it's better to have the image in the center of each cells. How to do it?
    thanks.

    Do you know how to make a JLabel which contains a centred icon? Now make a ListCellRenderer that uses one of those to render your images in the JList.

  • How to save JList items!

    hello,
    i m creating a class that has three JList components.
    My problem is how to save the each JList items into a seperate logfile(ie. text file).

    More info required:
    What are in the JList? Strings? Custom objects?
    Do you know basic file IO?
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    What you will need to do is get the model, ilterate over each element, then write that element out. If the element is a string, then that is easy, just create a FileWriter, and write the string, followed by a new line.
    If it is a custom object, then the task is harder, and you need to decide how that object should be represented.
    If you are after a computer readable view of the model, rather than a human readable, which can easily be read by Java back into a ListModel, then you want to look at XMLEncoder and XMLDecode, or the Serializing Objects tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • Dynamically changing size of JList items?

    Hello!
    I'm working on an application which kind of revolves around a JList with a custom ListCellRenderer. Now, it all works rather good as it is, but I want the selected JList item to show more detailed information about the selected value, and thus I need it to be bigger then the not selected items. The thing is that no matter what I do I can't seem to make the JList adopt to the new size of the selected item, which results in only half of the stuff in the selected item being shown.
    Is there any way to do this it would be great! (I bet there is some really simple way which I have simply overlooked.)
    And, fyi: The component returned by getListCellRendererComponent is a JPanel which consists of three JLabels using a GridLayout. The selected component is generally the same, but with an extra row in the GridLayout.
    Any help/suggestions will be greatly appreceated!
    Yours, Jiddo.

    I have tried with a couple of different layout managers, and none of them (except for this one) seems to offer me the layout I need. Also, I have tried making it return different instances depending on if it is selected or not. The non-selected one has only one row in the layout while the selected has two. Here is a screenshot of how it looks:
    http://img211.imageshack.us/img211/2779/jlistes1.jpg
    Yours, Jiddo.

  • Highlighting JList Items

    Hello
    Could anybody let me how to change the color of Few Items of JList. I know how to change the foreground color of an item which is selected. But, I need to show few items of JList in different color.
    Thanks in advance

    please can you tell us where is/are ..., could you able to demostrate your issue, now
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class JListDisabledItemDemo implements ItemListener, Runnable {
        private static final String ITEMS[] = {
            "Black", "Blue", "Green", "Orange", "Purple", "Red", "White", "Yellow"};
        private JList jList;
        private JCheckBox[] checkBoxes;
        private boolean[] enabledFlags;
        @Override
        public void run() {
            JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
            pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
            checkBoxes = new JCheckBox[ITEMS.length];
            enabledFlags = new boolean[ITEMS.length];
            for (int i = 0; i < ITEMS.length; i++) {
                checkBoxes[i] = new JCheckBox(ITEMS);
    checkBoxes[i].setSelected(true);
    checkBoxes[i].addItemListener(this);
    enabledFlags[i] = true;
    pnlEnablers.add(checkBoxes[i]);
    jList = new JList(ITEMS);
    jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jList.setSelectionModel(new DisabledItemSelectionModel());
    jList.setCellRenderer(new DisabledItemListCellRenderer());
    jList.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
    if (!e.getValueIsAdjusting()) {
    System.out.println("selection");
    JScrollPane scroll = new JScrollPane(jList);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    JFrame f = new JFrame("JList and Colors");
    Container contentPane = f.getContentPane();
    contentPane.setLayout(new GridLayout(1, 2));
    contentPane.add(pnlEnablers);
    contentPane.add(scroll);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(240, 280);
    f.setLocationRelativeTo(null);
    UIManager.put("List.background", Color.red);
    UIManager.put("List.selectionBackground", Color.orange);
    UIManager.put("List.selectionForeground", Color.blue);
    UIManager.put("Label.disabledForeground", Color.magenta);
    SwingUtilities.updateComponentTreeUI(f);
    f.setVisible(true);
    @Override
    public void itemStateChanged(ItemEvent event) {
    JCheckBox checkBox = (JCheckBox) event.getSource();
    int index = -1;
    for (int i = 0; i < ITEMS.length; i++) {
    if (ITEMS[i].equals(checkBox.getText())) {
    index = i;
    break;
    if (index != -1) {
    enabledFlags[index] = checkBox.isSelected();
    jList.repaint();
    public static void main(String args[]) {
    SwingUtilities.invokeLater(new JListDisabledItemDemo());
    private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
    private static final long serialVersionUID = 1L;
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (enabledFlags[index]) {
    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    Component comp = super.getListCellRendererComponent(list, value, index, false, false);
    comp.setEnabled(false);
    return comp;
    private class DisabledItemSelectionModel extends DefaultListSelectionModel {
    private static final long serialVersionUID = 1L;
    @Override
    public void setSelectionInterval(int index0, int index1) {
    if (enabledFlags[index0]) {
    super.setSelectionInterval(index0, index0);
    } else {
    if (getAnchorSelectionIndex() < index0) {
    for (int i = index0; i < enabledFlags.length; i++) {
    if (enabledFlags[i]) {
    super.setSelectionInterval(i, i);
    return;
    } else {
    for (int i = index0; i >= 0; i--) {
    if (enabledFlags[i]) {
    super.setSelectionInterval(i, i);
    return;

  • Double click for JList items selection

    I would like to select JList items only by double clicking on them. I can write a mouse listener for detecting double clicks by my own (and handle it afterwards), by please tell me how to turn the default behavior off (selecting items by clicking one time).
    Thanks in advance
    Marek

    I would like to select JList items only by double clicking on them. Well the standard is to select or highlight on a mouseClick or by using the arrow keys on the keyboard.
    Then once you have a selected item you can perform and Action on the item by double clicking or by using the enter key. Remember you should always be able to use either the keyboard or the mouse to perform any given function.
    This posting shows my solution for the above scenario:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866

  • Highlight a word within a JList Item

    I would like to highlight a word red within a JList item. For example, a user has a number of words to select from such as can or will. I would like them to select that word and any entries within the list I would like highlighted. I ONLY want the word within a JList item though and not the whole JList item. I know how to do this with a TextField but am having trouble doing this within a JList. Any help would be greatly appreciated.

    Use html syntax to set color/size of a list item. Try this simple example:
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame {
      public Testing() {
        String [] list = {
           "<html><body>Black <font size=15>Black</font> Black",
           "<html><body>Red <font color=red size=10>Red</font> Red ",
           "<html><body>Blue <font color=blue size=5>Blue</font> Blue"
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        JList jlist = new JList(list);
        JScrollPane spane = new JScrollPane(jlist);
        panel.add(spane);
        getContentPane().add(panel);
        setSize(200,200);
      public static void main(String[] args){
        new Testing().setVisible(true);
    }

  • Delete Selected JList Item on Pressing Delete Key

    Hi,
    I have to delete selected JList item ((in JFrame using java Swing) after pressing Delete key. Please provide me code for this.
    Thanks
    Nitin

    Again read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists and [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.
    Are you sensing a common theme here? Do some reading on your own. The tutorial has most of the information you need.

  • Editing Jlist Item Contents....

    hi,
    i want to edit the contents of a Jlist Item.
    any help???
    Manikandan

    in your ListSelectionListener you must check if the event is one of multiple change events. In your case you get one event when the mouse first selects an item and possible more when you move the cursor over the other entries. If you are only interested in the final selection check if e.getValueIsAdjusting() is false.
    // not interested in events if they are not final
    if (e.getValueIsAdjusting())
        return;
    // do what ever you want
    System.out.println(colorList.getSelectedValue());
    ...Hope this helps!

  • Icon in front of the JList items?

    Hola a todos,
    I am rendering a JList to a JTextArea and I want to add a icon in front of each of the items. First it can be the same icon later each one should become its own one.
    I am using this little piece of code to render the JList:
    JList lista_libros = new JList();
    lista_libros.setCellRenderer(new mirenderer());
    class mirenderer extends JTextArea implements ListCellRenderer
              public Component getListCellRendererComponent ( JList lista_libros, Object valor,
              int indice,     boolean seleccionado,boolean conFoco)
                   setBorder(new BevelBorder ( BevelBorder.RAISED));
                   setText (valor.toString());
                   //setIcon(new ImageIcon("libro1.gif"));
                   if (seleccionado)
                        setBackground (Color.blue);
                        setForeground (Color.white);
                   else
                        setBackground (Color.white);
                        setForeground (Color.black);
                   return this;
              } // getListCellRendererComponent()
         } // class mirenderer
    When I am using a JLabel instead of a JTextArea it is easy to add an icon, but the text is to long for only one line.
    Is it possible to add an icon to each item of the JList in the JTextArea?
    Chao
    Juergen

    Or is it possible to write a JLabel over moore than only one line?
    Chao
    Juergen

  • Permeantly select a JList Item.

    how would i permeantly select a item in a Jlist? ie. Even if the user clicks it it wont uncheck, it will always be selected.
    There will be other items in the Jlist which they may select and deselect but one which they cannot and stays selected.
    Thanks

    Hi,
    I would use the CellRenderer since selection if just the renderer drawing it. The example below should demonstrate what I mean.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class PermCellRenderer extends JLabel implements ListCellRenderer
      private int[] permIndices;
      public PermCellRenderer()
        this( null );
      public PermCellRenderer( int[] permIndices )
        setOpaque( true );
        this.permIndices = permIndices;
        System.out.println( this.permIndices[0] );
      private boolean isPermanent( int index )
        boolean outVal = false;
        if( permIndices != null )
          for( int i = 0; i < permIndices.length; ++i )
            if( permIndices[i] == index )
              outVal = true;
              break;
        return( outVal );
      public Component getListCellRendererComponent( JList list, Object value,
                                                     int index,
                                                     boolean isSelected,
                                                     boolean cellHasFocus )
        setText( value.toString() );
        if( isPermanent( index ) || isSelected )
          setBackground( list.getSelectionBackground() );
          setForeground( list.getSelectionForeground() );
        else
          setBackground( list.getBackground() );
          setForeground( list.getForeground() );
        return( this );
    public class PermListExample extends JFrame
      JList list;
      public PermListExample()
        super( "Permanent List Selection" );
        String[] data = { "First", "Second", "Permanent", "Fourth", "Fifth" };
        int[] perm = { 2 };
        list = new JList( data );
        list.setCellRenderer( new PermCellRenderer( perm ) );
        list.setVisibleRowCount( 10 );
        getContentPane().add( list );
        pack();
      public static void main(String[] args)
        new PermListExample().setVisible( true );
    }Enjoy,
    Manfred.

  • JList item selection

    I am using a JList, and I would like to select certain items in the list. Right now I am doing it by passing the constructor an array of int indecies that correspond to the items I want selected.
    What I would really like to do, is have one item selected in red and the others selected the way they are. Or the other way around. I just want different color selections. I'm pretty sure I can not do this, but I just wanted to see if you guys (and gals) had any ideas.
    The other idea I had was to use a JPanel, and then use drawString to list the items, then capture the mouse click, find what item was selected, and then paint that rectangle the color I want.

    Hi
    You need to write a custom ListCellRenderer and set that for the list using: list.setCellRenderer(someCellRenderer); Once you have done that, populate the list with items (i.e. instances of a class which you created) that define whether the list item being drawn should be drawn using a red foreground. The renderer will need to check and see if the list item boolean value for painting in red is true, and if so set the foreground to red, otherwise use the default foreground color.
    Sorry if this sounds cryptic but I can't devote any more time to helping you out. Best of luck.
    cheers,
    Greg

  • Clicking (and selecting) the same JList item twice

    I have a JList with items (Strings) which should be added to another String when selected (clicked on). My problem is that when a user clicks twice on the same item it should be added to the result String twice. But a ListSelectionListener acts only when the value has changed, so when an other item is selected.
    Does anyone know a neat (as high level as possible) solution for this?
    P.S.: How do you assign duke dollars to a topic? And how do you give someone who replies those?

    Thanks. I also already thought of adding a MouseListener, but I kind of wanted to avoid it. But it seems that it is necessary if I want to keep the selection.
    The solution I have now, by the way, is that I set the selectedIndex back to -1 in valueChanged, so there is never any item selected.

  • Selection of JList item

    hi friends
    i am using JList component.i have added many item in Jlist.by keyboard up and down arrow key i can make them highlighted and then select. but i want few item of JList never highlighted and select when i press up and down arrow key . For example, If i do not want to select 2nd item in the list then by pressing down arrow key selection should be jumped from first to third item skipping second item.
    How to do that?

    I might be wrong but I think you need to code for it.
    I have created a code using key binding. To use if you need to skip an item you need to hold down the control key and use the up and down arrow to navigate and once you have selected an item release control key and press enter, vice-versa.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ListFocusDemo extends JFrame {
        public void createAndShowUI() {
            final JList myList = new JList(new String[] {"My data 1","My data 2",
            "My data 3","My data 4"});
            JScrollPane scrollPane = new JScrollPane(myList);
            InputMap map = myList.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "myAction");
            myList.getActionMap().put("myAction", new AbstractAction() {
                public void actionPerformed(ActionEvent evt) {
                    int lead = myList.getLeadSelectionIndex();
                    if(lead > -1 && !myList.isSelectedIndex(lead)) {
                        myList.getSelectionModel().addSelectionInterval(lead, lead);
                    } else if(lead > -1 && myList.isSelectedIndex(lead)) {
                        myList.getSelectionModel().removeSelectionInterval(lead, lead);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        public static void main(String[] args) {
            Runnable run = new Runnable() {
                public void run() {
                    new ListFocusDemo().createAndShowUI();
            SwingUtilities.invokeLater(run);
    }

  • Can we implement partial page rendering on item style Flex??

    Hi All,
    In an xml,
    I have item style 'Flex' for expense account.
    Requirement is :
    In the same page i have other LOV which brings the data based on one of the segments of that expense account.
    So any changes in one of the segments for the expesne account need to be stored and LOV query should be modified accrodingly..
    So trying with following possibilties
    1) Use partial page rendering for expense account
    2) Split the page into two so that first expense account is displayed and any modifications to it are handled in controller and use LOV Mappings to update the query.
    So can partial page rendering can be implemented for Item style "Flex".
    Can anyone please provide the inputs to handle this scenario and best possible solution?
    Issue is very hot right now.. Quick help needed..

    Hi
    No u can not use PPR for flex items although u can create context flexfield .
    thanx
    Pratap

Maybe you are looking for