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

Similar Messages

  • 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

  • JList item selected is displayed twice. Please Assist

    Folks,
    I have this strange behaviour when I select an item from the JList.
    When I select the an item, it gets displayed twice.
    Can anyone tell me why this is being displayed twice?
    I am also checking the Java Sun Swing tutorials site..but no luck as yet.
    Attached is a short class.
    If you click on Black or Blue etc ,it gets displayed twice...
    public class JListDemo extends JFrame{
    private JList colorList;
    private Container c;
    private String colorNames[] = {"Black", "Blue","Red","Green","Yellow"};
    public JListDemo() {
    super("JList Demo");
    c = getContentPane();
    c.setLayout(new FlowLayout());
    /** Create a List */
    colorList = new JList(colorNames);
    colorList.setVisibleRowCount(3);
    colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    c.add(new JScrollPane(colorList));
    //** Set up Event Handler.
    colorList.addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e)
    System.out.println(colorList.getSelectedValue());
    setSize(1000,550);
    show();
    public static void main(String[] args) {
    JListDemo JListDemo1 = new JListDemo();
    }

    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!

  • JList item selected displayed Twice...Please suggest

    Folks,
    The selected value from the JList is being displayed twice.
    I am unable to figure out why this is being displayed twice.
    Can anyone suggest??
    If you click Black..it will de displayed twice!!!!
    public class JListDemo extends JFrame{
    private JList colorList;
    private Hashtable ht;
    private Container c;
    private String colorNames[] = {"Black", "Blue","Red","Green","Yellow"};
    public JListDemo() {
    super("JList Demo");
    c = getContentPane();
    c.setLayout(new FlowLayout());
    //** Create a List
    colorList = new JList(colorNames);
    colorList.setVisibleRowCount(3);
    colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    c.add(new JScrollPane(colorList));
    //** Set up Event Handler.
    colorList.addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e)
    System.out.println(colorList.getSelectedValue());
    setSize(1000,550);
    show();
    public static void main(String[] args) {
    JListDemo JListDemo1 = new JListDemo();
    So if you click

    Sure, the Swing tutorial on "Using Lists" will explain whats happening and give you a solution:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#selection

  • 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.

  • Attempting to Get Specific Items Selected from a JList

    Hello all, back again...
    I'm working on a simple interface that can run an SQL query with specific settings, and these settings can be altered by choosing one or multiple options from a JList to the side of the table that displays the results. My problem is, currently, not being able to figure out how to get the accursed thing to tell me what items in the JList are selected!
    I've tried using:
    int multiselect[] = cmbSystems.getSelectedIndices();...but it inevitably returns an array with a size of 1. Frustrating. I know I'm missing something, but I have no idea what. What am I doing wrong? Thanks!
    ~ Matt

    Mystrunner wrote:
    Hmm, okay... give me a bit to figure that out, and I will. :)Sure. Your SSCCE should probably only consist of a JList that prints out the selected items when the selection changes, or something like that. I would bet that you figure out what's going wrong in the process of boiling your code down to the SSCCE.

  • How to delete items selected in a JList?

    Ahoy,
    I hava made a Multiple selection list (two list: one for
    the items that might be selected and another one
    for the selected items). How can I delete the (faultly) selected items in the second list?
    Thanx,
    // create function button
    copy = new JButton( ">>" );
    delete = new JButton ( "<<");
    copy.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
    // place selected values in functionList
    copyList.setListData(
    functionList.getSelectedValues() );     
    delete.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
    // delete selected items from copyList
    );

    You must get the selected item and remove from the model...
    delete.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    int si = list.getSelectedIndex(); //get the index of the item selected
    if (si > -1) {   //to validate that be selected
    listModel.removeElementAt(si);  //remove from the listmodel
    modifyTextField.setText("");  
    });in this url you can see a complete sample..
    http://www.esus.com/javaindex/j2se/jdk1.2/javaxswing/atomiccontrols/jlist/addtojlist.html

  • Key pressed in Jlist and selecting the item of key list accordingly

    Hi,
    I have a JList with the items in sorted order.Now I want that if a person presses any key (say K) then the first item starting with K should be selected.Hmmm I can do it by addding a key listener to the list and cheking all the items in the list ,by traversing through the whole lenght of JList and selecting the item if it starts with the character of the key pressed.
    But i was thinking if there is any better way to do that?
    Regards Amin

    see bugid: 4654916 - it does say that the the
    scrolling for the JList should now work with keyboard
    selection.I have the same problem. Thanx for the hint with the bugid. Saw a good workaround there with a simple subclass of JList. Works for me although it is annoying to subclass JList all the time. The bug seems not to be fixed in the 1.4.1 JDK.
    Andreas

  • Selected item in a JList - Clear selection after mouse click

    Hello:
    I'm developing a Java GUI application which uses some JLists. I've seen that, when an item of the JList is selected and you click the mouse another time in the same selected item, the selection does not "disappear". Now, the only way I know to do this is tho press Control + click in the selected item.
    I would like that, when I click to the selected item of a list, the selection disappears.
    How can I solve that?
    Lots of thanks for your help.

    add a MouseListener to the list
    in mouseReleased (note: Released), get the selected index
    compare to previous selection - if the same, list.clearSelection()
    if you clear the selection, you'll need to reset the 'previous selection' variable

  • 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.

  • Selecting jList items

    Hi!
    I'm developing a image browser app using JList. I'm having problems with a contextual popup menu. When I click on an image from the JList I show the popup with some options related to the image (delete,
    paste, etc ...),
    But when I click on an empty zone in the JList, the last item gets selected and the same popup gets shown even though I didn't click any item.
    1) what should i do so that no item in the jlist is selected when i click in its empty zones
    2) how do i make a different set of menuitems be enabled or disabled which i click on the empty zones
    Thanks in adavance
    kalpana

    1) what should i do so that no item in the jlist is sselected when i click in its empty zonesYou may have to override JList's locationToIndex(Point p) method so that it returns -1 (or probably the currently selected index) when the point is not located in any of the list items. I believe by default, this selects the closets index to the point.
    2) how do i make a different set of menuitems be enabled or disabled which i click on the empty zonesYou have to provide some sort of manager class or interface where the popup menu can go to obtain the state of the image in the list, and enable or disable the menuItems as necessary.
    ICE

  • 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;

  • 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);
    }

  • 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!

Maybe you are looking for

  • How to restore the original copy of OS.

    The hard disk of my notebook got damaged and now I have installed new hard disk but since I didnt had any backup the windows 8.1 OS also got lost. Now I have installed trial version, can anyone let me know how to restore the original copy of OS. 

  • Need host string for xp  machine (oracle 10.1.1..2)

    Hi: my email address is [email protected] need host string or how to get information for host string. Thank You wayne

  • "\n" in content pane

    Hi. How can I do something similar to a "\n" in a getContentPane? I think that is something like label1 = new JLabel( bug, SwingConstants."HERE GOES THE "\N"); Thanks

  • How do I format my new ipod for windows?

    I already have itunes 7 on my computer. I have read that the ipods come formatted for a mac, and you need to format them for windows. I have read about opening the updater. The updated is not listed as a program on my computer. I also would not want

  • Case sensitivity of Cisco UC Apps - CSCur00659

    Hi, Can someone tell the Cisco developers (all of them, in general) that usersnames should NEVER be handled with case!?! Finesse Agent login is case sensitive, doesn't remember extension and doesn't auto-logout when we close the browser (UCCX 10.5(1)