JList's setSelectedValue

Hi!
I'm using the "setSelectedValue" method from the JList class to
select an item from a list of objects extending a class I developed named "Transition". This is the code I cannot get to work:
DefaultListModel model=new DefaultListModel();
JList list=new JList(model);
model.addElement(new DefaultTransition());
model.addElement(new FadeTransition());
Transition transition=getTransition();
list.setSelectedValue(transition,true);
I supposed the "setSelectedValue" method would select one of the two
items in the list but nothing gets selected. What am I doing wrong ?
Thanks in advance

Either getTransition() has to return one of the actual objects in the list or Transition needs to override the equals() method.

Similar Messages

  • By default a item in a JList should selected

    Hi
    I need a item in the JList should be selected(not the first item) by default while I am creating a new instances for the JList.
    Note: I am rendering a button in the JList.
    with regrads
    senthil kumar

    You should be able to use either of the following methods of JList: setSelectedIndex(defaultIndex); or setSelectedValue(defaultObject, shouldScroll);Is one of these what you are looking for?

  • Jlist with disabled selection mode

    Hello,
    I want a Jlist where i can switch from noselection possible to singleselection whenever i want to,
    Single selection is no problem,
    but no selection i founded only to disable the jlist, and thats no option.
    Any suggestions,
    thx in adv.
    Donovan.

    Hi,
    this should do, maybe you need to implement a constructor:public class MyList extends JList {
         private boolean selectAllowed = true;
         public void setSelectedIndex(int index) {
              if (!selectAllowed) {
                   return;
              super.setSelectedIndex(index);
         public void setSelectedIndices(int[] indices) {
              if (!selectAllowed) {
                   return;
              super.setSelectedIndices(indices);
         public void setSelectedValue(Object anObject, boolean shouldScroll) {
              if (!selectAllowed) {
                   return;
              super.setSelectedValue(anObject, shouldScroll);
         public void setSelectionAllowed(boolean allowed){
              if (!allowed) {
                   super.clearSelection();
              selectAllowed = allowed;

  • JOptionPane.showInputDialog with a JList?

    Is there any quick and easy way to use the JOptionPane.showInputDialog with a JList? the default is a drop down menu. Thanks!

    Is there any quick and easy way to use the
    JOptionPane.showInputDialog with a JList? the default
    is a drop down menu. Thanks!I have found a way to this. You need to write your own JOptionPane
    class MyJOptionPane
        public static Object showListInputDialog(Component parentComponent, Object message, String title, Object[] selecttionValues)
            Object defaultOptionPaneUI = UIManager.get("OptionPaneUI");
            UIManager.put("OptionPaneUI", "MyBasicOptionPaneUI");
            Object object = JOptionPane.showInputDialog(parentComponent, message, title, JOptionPane.PLAIN_MESSAGE, null,
                    selecttionValues, selecttionValues[0]);
            UIManager.put("OptionPaneUI", defaultOptionPaneUI);
            return object;
    }And then create your own MyBasicOptionPaneUI extending from javax.swing.plaf.basic.BasicOptionPaneUI with 2 methods overridden. The codes are copied from javax.swing.plaf.basic.BasicOptionPaneUI and modified to get rid of JComboBox.
    public class MyBasicOptionPaneUI extends BasicOptionPaneUI
        public MyBasicOptionPaneUI()
            super();
        public static ComponentUI createUI(JComponent x) {
             return new MyBasicOptionPaneUI();
        protected Object getMessage()
            inputComponent = null;
            if (optionPane != null) {
                if (optionPane.getWantsInput()) {
                    /* Create a user component to capture the input. If the
                       selectionValues are non null  with any size ,
                       it'll be a list, otherwise it'll be a textfield. */
                    Object message = optionPane.getMessage();
                    Object[] sValues = optionPane.getSelectionValues();
                    Object inputValue = optionPane
                            .getInitialSelectionValue();
                    JComponent toAdd;
                    if (sValues != null) {
                            JList list = new JList(sValues);
                            JScrollPane sp = new JScrollPane(list);
                            list.setVisibleRowCount(10);
                            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                            if (inputValue != null)
                                list.setSelectedValue(inputValue, true);
                            list.addMouseListener(new ListSelectionListener());
                            toAdd = sp;
                            inputComponent = list;
                    } else {
                        MultiplexingTextField tf = new MultiplexingTextField(20);
                        tf.setKeyStrokes(new KeyStroke[]{
                            KeyStroke.getKeyStroke("ENTER")});
                        if (inputValue != null) {
                            String inputString = inputValue.toString();
                            tf.setText(inputString);
                            tf.setSelectionStart(0);
                            tf.setSelectionEnd(inputString.length());
                        tf.addActionListener(new TextFieldActionListener());
                        toAdd = inputComponent = tf;
                    Object[] newMessage;
                    if (message == null) {
                        newMessage = new Object[1];
                        newMessage[0] = toAdd;
                    } else {
                        newMessage = new Object[2];
                        newMessage[0] = message;
                        newMessage[1] = toAdd;
                    return newMessage;
                return optionPane.getMessage();
            return null;
        private static class MultiplexingTextField extends JTextField
            private KeyStroke[] strokes;
            MultiplexingTextField(int cols)
                super(cols);
             * Sets the KeyStrokes that will be additional processed for
             * ancestor bindings.
            void setKeyStrokes(KeyStroke[] strokes)
                this.strokes = strokes;
            protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                                                int condition, boolean pressed)
                boolean processed = super.processKeyBinding(ks, e, condition,
                        pressed);
                if (processed && condition != JComponent.WHEN_IN_FOCUSED_WINDOW) {
                    for (int counter = strokes.length - 1; counter >= 0;
                         counter--) {
                        if (strokes[counter].equals(ks)) {
                            // Returning false will allow further processing
                            // of the bindings, eg our parent Containers will get a
                            // crack at them.
                            return false;
                return processed;
        private class ListSelectionListener extends MouseAdapter
            public void mousePressed(MouseEvent e)
                if (e.getClickCount() == 2) {
                    JList list = (JList) e.getSource();
                    int index = list.locationToIndex(e.getPoint());
                    optionPane.setInputValue(list.getModel().getElementAt(index));
        private class TextFieldActionListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                optionPane.setInputValue(((JTextField) e.getSource()).getText());
    }

  • How t print out selected values from a Jlist

    hi iam trying to get the selected values from a list to print out as a string but iam getting ,Invalid cast from java.lang.Object[] to java.lang.String.is there any way to get the selected values t print ut as a string?? import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MultipleSelection2 extends JFrame {
    private JList colorList, copyList;
    private JButton copy;
    private String colorNames[] =
    { "Black", "Blue", "Cyan", "Dark Gray", "Gray",
    "Green", "Light Gray", "Magenta", "Orange", "Pink",
    "Red", "White", "Yellow" };
    public MultipleSelection2()
    super( "Multiple Selection Lists" );
    Container c = getContentPane();
    c.setLayout( new FlowLayout() );
    colorList = new JList( colorNames );
    colorList.setVisibleRowCount( 5 );
    colorList.setFixedCellHeight( 15 );
    colorList.setSelectionMode(
    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    c.add( new JScrollPane( colorList ) );
    // create copy button
    copy = new JButton( "Copy >>>" );
    copy.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
    // place selected values in copyList
    copyList.setListData(
    colorList.getSelectedValues());
    String s1 =(String)colorList.getSelectedValues();

    Since the JList method 'getSelectedValues' returns an object array you'll need to iterate through the array and cast each object in the array to a string as you access them.
    Object[] o = colorList.getSelectedValues();
    for(int count=0,end=o.length; count<end; count++) {
    String s = (String) o[count];
    Hope that helps
    Talden

  • Getting all the values from a JList

    Hi,
    I want to get all the values from a JList and store it into an array. Any method is available to perform this task? Pls help me out with this task.

    Use getModel() on the list to get the ListModel and then call getSize() and getElementAt(int) to loop over the elements
    HTH
    Mike

  • I want to insert some checkboxes in a JList

    ...is it possible?
    I tried, but it inserts a string!
    This is my code:
    JList list = new JList();
    panel.add(list);
    CheckBox check = new JCheckBox("Yes");
    DefaultListModel model = new DefaultListModel();
    model.addElement(check);
    list.setModel(model);
    // I am able to see only the String "javax.swing.JCheckBox[,0,0,0x0, invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorder.....text=User Prefix]"
    Thank you!

    Hi Sorin,
    you can aquire your data in a loop and use shift registers to store your data (use an array). To get the maximum of the array there is a function in labview "Array Max & Min".
    Hope this helps.
    Mike

  • 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

  • Populating JList with a single database column

    Hi all,
    I have the following code and i'm trying to popluate the JList with a particular colum from my MySQL Database..
    how do i go about doing it??
    Can some one please help
    import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class RemoveD extends JDialog {     private JList list;     private JButton removeButton;     private JScrollPane scrollPane;     private Connection conn = null;     private Statement stat = null;         public RemoveD(Frame parent, boolean modal) {         super(parent, modal);         initComponents();     }     private void initComponents() {         scrollPane = new JScrollPane();         list = new JList();         removeButton = new JButton();         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);         getContentPane().setLayout(new GridLayout(2, 0));         scrollPane.setViewportView(list);         getContentPane().add(scrollPane);         removeButton.setText("Remove");         removeButton.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent evt) {                 removeButtonActionPerformed(evt);             }         });         getContentPane().add(removeButton);         pack();         try {             Class.forName("com.mysql.jdbc.Driver");                    } catch (ClassNotFoundException ex) {             ex.printStackTrace();                    }         try {             String userID = "";             String psw = "";             String url;             url = "jdbc:mysql://localhost:3306/names";             conn = DriverManager.getConnection(url, userID, psw);             stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,                     ResultSet.CONCUR_READ_ONLY);             stat.close();             conn.close();         } catch (SQLException ex) {             ex.printStackTrace();         }     }     private void removeButtonActionPerformed(ActionEvent evt) {     }     public static void main(String args[]) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 RemoveD dialog = new RemoveD(new JFrame(), true);                 dialog.addWindowListener(new WindowAdapter() {                     public void windowClosing(WindowEvent e) {                         System.exit(0);                     }                 });                 dialog.setVisible(true);             }         });     } }

    I figured out how to do it

  • How to print text from Textfield onto JList?

    Hi!I've typed a sentence on the textfield,and wat can i do to print out this sentence onto the JList i've created,after clicking on my JButton"Post".And on the JList,there must be numbering for each sentence.And New sentences will directly be added after the previous sentence.Hope to get a quick reply from any helpful people.Thanks.

    This should do it. (Typed straight in so untested).
    // create components and event listener
    JTextField textField = new JTextField();
    final DefaultListModel listModel = new DefaultListModel();
    JList list = new JList(listModel);
    JButton button = new JButton("Add");
    button.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent ev)
            String text = textField.getText();
            listModel.add(text);
    // now display them

  • How to  move items from one JList to other

    Can u pls help me out to implement this(I m using Netbeans 5.5):
    I want to move items from one JList to other thru a ADD button placed between JLists, I am able to add element on Right side JList but as soon as compiler encounter removeElementAt() it throws Array Index Out of Bound Exception
    and if I use
    removeElement() it removes all items from left side JList and returns value false.
    Pls have a look at this code:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    Object selItem = jList1.getSelectedValue();
    int selIndex = jList1.getSelectedIndex();
    DefaultListModel model = new DefaultListModel();
    jList2.setModel(model);
    model.addElement(selItem);
    DefaultListModel modelr = new DefaultListModel();
    jList1.setModel(modelr);
    flag = modelr.removeElement(selItem);
    //modelr.removeElementAt(selIndex);
    System.out.println(flag);
    }

    hi Rodney_McKay,
    Thanks for valuable time but my problem is as it is, pls have a look what I have done and what more can b done in this direction.
    Here is the code:
    import javax.swing.DefaultListModel;
    import javax.swing.JList;
    public class twoList extends javax.swing.JFrame {
    /** Creates new form twoList */
    public twoList() {
    initComponents();
    //The code shown below is automatically generated and we can�t edit this code
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jList1 = new javax.swing.JList();
    jButton1 = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    jList2 = new javax.swing.JList();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jList1.setModel(new javax.swing.AbstractListModel() {
    String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
    public int getSize() { return strings.length; }
    public Object getElementAt(int i) { return strings[i]; }
    jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
    public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
    jList1ValueChanged(evt);
    jScrollPane1.setViewportView(jList1);
    jButton1.setText("ADD>>");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jScrollPane2.setViewportView(jList2);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(31, 31, 31)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(78, Short.MAX_VALUE))
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(62, 62, 62)
    .addComponent(jButton1))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
    .addContainerGap(159, Short.MAX_VALUE))
    layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});
    pack();
    }// </editor-fold>
    //automatic code ends here
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            jList1 = new JList(new DefaultListModel());
            jList2 = new JList(new DefaultListModel());
             Object selItem = jList1.getSelectedValue();
             System.out.println(selItem);
            ((DefaultListModel) jList1.getModel()).removeElement(selItem);
            ((DefaultListModel) jList2.getModel()).addElement(selItem);
    //Now trying with this code it is neither adding or removing and the value �null� is coming in �selItem� .It may be bcoz JList and Jlist are already instantiated in automatic code. So, I tried this:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
             Object selItem = jList1.getSelectedValue();
             System.out.println(selItem);
            ((DefaultListModel) jList1.getModel()).removeElement(selItem);
            ((DefaultListModel) jList2.getModel()).addElement(selItem);
    //Now with this as soon as I click on �jButton1�, it is throwing this error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: twoList$1 cannot be cast to javax.swing.DefaultListModel
            at twoList.jButton1ActionPerformed(twoList.java:105)
            at twoList.access$100(twoList.java:13)
            at twoList$3.actionPerformed(twoList.java:50)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

  • Moving stuff from one JList to an other

    Hi,
    I'm trying to develop a JPanel with two JLists and two arrow JButtons to be able to move (!) stuff from the left JList to the Right and backwards. Both JLists have a ListCellRenderer that extend JLabel.
    Managed to do a 'copy' of selected values to the other JList,
    eg.
    public void addKeyWords(java.awt.event.ActionEvent actionEvent,javax.swing.JList allKeyWords,javax.swing.JList chosenKeyWords) {
    java.util.List chosenValues = java.util.Arrays.asList(chosenKeyWords.getSelectedValues());
    java.util.List selectedValues = java.util.Arrays.asList(allKeyWords.getSelectedValues());
    java.util.Set set = new java.util.HashSet();
    set.addAll(selectedValues);
    javax.swing.JList l = new javax.swing.JList(set.toArray());
    getChosenKeyWordsList().setModel(l.getModel());
    return;
    but can't figure out how to get stuff to disappear in the first JList when it is moved to the other JList nore how to enable the user to 'add' elements one at a time.
    Enyone?

    hi.
    what i do when i want to remove from the right side list:
    //get an array of indexes that needs to be removed.
    elements[] removedItems = getStrings(rightListData, selected);
    //copy all elements that do NOT need to be removed
    rightListData = utils.copyArrayWithoutIndex(rightData, selected);
    rightList.setListData(rightListData);
    same goes for left side.
    basically, i remove all selected elements from the array of rows, and re-set the list data model.
    HTH.

  • How can I keep the selectedIndex of two JLists the same?

    I have two independant JLists. I have one button to add items from two textfields to the lists. I also have one button to remove the selected items from the lists. However because the items in both JLists are related I want to make sure the selected index of one is always equal to the selected index of the other. HOW!

    OK, so here is the current code, there must be an easy way to do it, Swing gurus please help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class ListDemo extends JFrame
                          implements ListSelectionListener {
        private JList list;
        private JList list2;
        private DefaultListModel listModel;
        private DefaultListModel listModel2;
        private static final String hireString = "Add";
        private static final String fireString = "Remove";
        private JButton fireButton;
        private JTextField employeeName;
        private JTextField percent;
        private JSlider per;
        public ListDemo() {
            super("ListDemo");
            listModel = new DefaultListModel();
            listModel.addElement("Alison Huml");
            listModel.addElement("Kathy Walrath");
            listModel.addElement("Lisa Friendly");
            listModel.addElement("Mary Campione");
            listModel2 = new DefaultListModel();
            listModel2.addElement("100");
            listModel2.addElement("80");
            listModel2.addElement("50");
            listModel2.addElement("10");
            //Create the list and put it in a scroll pane
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            //Create the percentlist and put it in a scroll pane
            list2 = new JList(listModel2);
            list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list2.setSelectedIndex(0);
            list2.addListSelectionListener(this);
            JScrollPane listScrollPane2 = new JScrollPane(list2);
            JButton hireButton = new JButton(hireString);
            hireButton.setActionCommand(hireString);
            hireButton.addActionListener(new HireListener());
            fireButton = new JButton(fireString);
            fireButton.setActionCommand(fireString);
            fireButton.addActionListener(new FireListener());
            employeeName = new JTextField(10);
            employeeName.addActionListener(new HireListener());
            String name = listModel.getElementAt(
                                  list.getSelectedIndex()).toString();
            employeeName.setText(name);
            per = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
            per.setMajorTickSpacing(10);
            per.setPaintTicks(true);
            per.setPaintLabels(true);
            percent = new TextField(10);
            percent.setValue(new Integer(1));
            percent.addActionListener(new HireListener());
            String name2 = listModel2.getElementAt(
                                  list2.getSelectedIndex()).toString();
            percent.setText(name2);
            //Create a panel that uses FlowLayout (the default).
            JPanel buttonPane = new JPanel();
            buttonPane.add(employeeName);
            buttonPane.add(per);
            buttonPane.add(hireButton);
            buttonPane.add(fireButton);
            Container contentPane = getContentPane();
            contentPane.add(listScrollPane, BorderLayout.CENTER);
            contentPane.add(listScrollPane2, BorderLayout.EAST);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
        class FireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //This method can be called only if
                //there's a valid selection
                //so go ahead and remove whatever's selected.
                int index = list.getSelectedIndex();
                int index2 = list2.getSelectedIndex();
                listModel.remove(index);
                listModel2.remove(index2);
                int size = listModel.getSize();
                int size2 = listModel2.getSize();
                if (size == 0) {
                //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else {
                //Adjust the selection.
                    if (index == listModel.getSize())//removed item in last position
                        index--;
                    list.setSelectedIndex(index);   //otherwise select same index
                if (size2 == 0) {
                //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else {
                //Adjust the selection.
                    if (index2 == listModel2.getSize())//removed item in last position
                        index2--;
                    list2.setSelectedIndex(index2);   //otherwise select same index
        //This listener is shared by the text field and the hire button
        class HireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //User didn't type in a name...
                if (employeeName.getText().equals("")) {
                    Toolkit.getDefaultToolkit().beep();
                    return;
                //User didn't type in a percent...
                if (percent.getText().equals("")) {
                    Toolkit.getDefaultToolkit().beep();
                    return;
                int index = list.getSelectedIndex();
                int index2 = list2.getSelectedIndex();
                int size = listModel.getSize();
                int size2 = listModel2.getSize();
                //If no selection or if item in last position is selected,
                //add the new hire to end of list, and select new hire.
                if (index == -1 || (index+1 == size)) {
                    listModel.addElement(employeeName.getText());
                    list.setSelectedIndex(size);
                //Otherwise insert the new hire after the current selection,
                //and select new hire.
                } else {
                    listModel.insertElementAt(employeeName.getText(), index+1);
                    list.setSelectedIndex(index+1);
                //If no selection or if item in last position is selected,
                //add the new hire to end of list, and select new hire.
                if (index2 == -1 || (index2+1 == size2)) {
                    listModel2.addElement(String.valueOf(per.getValue()));
                    list2.setSelectedIndex(size2);
                //Otherwise insert the new hire after the current selection,
                //and select new hire.
                } else {
                    listModel2.insertElementAt(String.valueOf(per.getValue()), index2+1);
                    list2.setSelectedIndex(index2+1);
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (list.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
                    employeeName.setText("");
                } else {
                //Selection, update text field.
                    fireButton.setEnabled(true);
                    String name = list.getSelectedValue().toString();
                    employeeName.setText(name);
                if (list2.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
    //                percent.setText("");
                } else {
                //Selection, update text field.
                    fireButton.setEnabled(true);
                    String name = list2.getSelectedValue().toString();
    //                percent.setText(name);
        public static void main(String s[]) {
            JFrame frame = new ListDemo();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

  • SetSelectedValue for multiple values in List Box

    Hi,
    I want to set the selectedValue for multiple values in the List Box. If i use setSelectedValue for all the values, it just highlights the last one.
    Can anyone tell me how do i highlight multiple values in the List Box?
    Scenario:
    I have one screen where the List Box and "Go" button is placed. When i select multiple values in the list box and hit "Go" it should display what i have selected in the List Box.
    Note: List Box is generated dynamically.
    Thanks,
    Naresh V

    setSelectedValue as the name indicates will set one value and in your case since you are using it multiple times it would pick the last value.
    When the user selects multiple values from the list box and clicks on Go you can capture those values in the controller for processing. What are you trying to achieve by resetting all the selected values on the same listbox ?

Maybe you are looking for