Selecting an item twice in JList

Hy,
I have create a JList with some animal's name in it. When I click on one of the animal's
name for the FIRST time, it appears in a JTextArea.
What I want is that when I click on that same name consecutively, it appears again in that
JTextArea. Can anyone please send me the code for doing that. Its very urgent.
Here are my code:
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PropertyWindow extends JFrame implements ListSelectionListener, ActionListener {
     private JList list;
     private JScrollPane scrollTextArea;
     private JTextArea textArea;
     private String text;
     private Vector imageNames;
     private JLabel picture;
     private DefaultListModel listModel;
     public PropertyWindow () {
          super("Property Window");
          //create a text area
          textArea = new JTextArea();
          textArea.setFont(new Font("Arial", Font.PLAIN, 16));
          textArea.setLineWrap(true);
          textArea.setWrapStyleWord(true);
          //create a scrollpane and add it to the text area
          scrollTextArea = new JScrollPane(textArea);
          scrollTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scrollTextArea.setPreferredSize(new Dimension(200,35));
          //create a list of button and add it to the JPanel
          JButton addButton = new JButton("+");
          JButton subtractButton = new JButton("-");
          JButton multiplyButton = new JButton("x");
          JButton divideButton = new JButton("/");
          JButton assignButton = new JButton("=");
          JButton equalButton = new JButton("= =");
          JButton greaterButton = new JButton(">");
          JButton G_EqualButton = new JButton("> =");
          JButton lessButton = new JButton("<");
          JButton L_EqualButton = new JButton("< =");
          JButton notEqualButton = new JButton("! =");
          JButton oneButton = new JButton("1");
          JButton twoButton = new JButton("2");
          JButton threeButton = new JButton("3");
          JButton fourButton = new JButton("4");
          JButton fiveButton = new JButton("5");
          JButton sixButton = new JButton("6");
          JButton sevenButton = new JButton("7");
          JButton eightButton = new JButton("8");
          JButton nineButton = new JButton("9");
          JButton zeroButton = new JButton("0");
          addButton.setActionCommand ("+");
          subtractButton.setActionCommand("-");
          multiplyButton.setActionCommand("x");
          divideButton.setActionCommand ("/");
          assignButton.setActionCommand ("=");
          equalButton.setActionCommand ("= =");
          greaterButton.setActionCommand (">");
          G_EqualButton.setActionCommand ("> =");
          lessButton.setActionCommand ("<");
          L_EqualButton.setActionCommand ("< =");
          notEqualButton.setActionCommand("! =");
          oneButton.setActionCommand ("1");
          twoButton.setActionCommand ("2");
          threeButton.setActionCommand ("3");
          fourButton.setActionCommand ("4");
          fiveButton.setActionCommand ("5");
          sixButton.setActionCommand ("6");
          sevenButton.setActionCommand ("7");
          eightButton.setActionCommand ("8");
          nineButton.setActionCommand ("9");
          zeroButton.setActionCommand ("0");
          JPanel buttonPane = new JPanel();
          buttonPane.setBorder(
                                        BorderFactory.createCompoundBorder(
                                   BorderFactory.createCompoundBorder(
                              BorderFactory.createTitledBorder("Arithmetic/Logical Operations"),
                              BorderFactory.createEmptyBorder(5,5,5,5)),
                                   buttonPane.getBorder()));
          buttonPane.setLayout(new GridLayout (3,7));
          buttonPane.add(addButton);
          buttonPane.add(subtractButton);
          buttonPane.add(multiplyButton);
          buttonPane.add(divideButton);
          buttonPane.add(assignButton);
          buttonPane.add(equalButton);
          buttonPane.add(greaterButton);
          buttonPane.add(G_EqualButton);
          buttonPane.add(lessButton);
          buttonPane.add(L_EqualButton);
          buttonPane.add(notEqualButton);
          buttonPane.add(oneButton);
          buttonPane.add(twoButton);
          buttonPane.add(threeButton);
          buttonPane.add(fourButton);
          buttonPane.add(fiveButton);
          buttonPane.add(sixButton);
          buttonPane.add(sevenButton);
          buttonPane.add(eightButton);
          buttonPane.add(nineButton);
          buttonPane.add(zeroButton);
          addButton.addActionListener(this);
          subtractButton.addActionListener(this);
          multiplyButton.addActionListener(this);
          divideButton.addActionListener(this);
          assignButton.addActionListener(this);
          equalButton.addActionListener(this);
          greaterButton.addActionListener(this);
          G_EqualButton.addActionListener(this);
          lessButton.addActionListener(this);
          L_EqualButton.addActionListener(this);
          notEqualButton.addActionListener(this);
          oneButton.addActionListener(this);
          twoButton.addActionListener(this);
          threeButton.addActionListener(this);
          fourButton.addActionListener(this);
          fiveButton.addActionListener(this);
          sixButton.addActionListener(this);
          sevenButton.addActionListener(this);
          eightButton.addActionListener(this);
          nineButton.addActionListener(this);
          zeroButton.addActionListener(this);
          //create the 'ok' and 'cancel' button
          JButton okButton = new JButton("Ok");
          JButton cancelButton = new JButton("Cancel");
          okButton.setActionCommand("Ok");
          okButton.addActionListener(this);
          cancelButton.setActionCommand("Cancel");
          cancelButton.addActionListener(this);
          JPanel controlPane = new JPanel();
          controlPane.setLayout(new FlowLayout());
          controlPane.add(okButton);
          controlPane.add(cancelButton);
          //create a Jlist where to insert variables
          listModel = new DefaultListModel();
listModel.addElement("dog");
listModel.addElement("cat");
listModel.addElement("rat");
listModel.addElement("rabbit");
listModel.addElement("cow");
          list = new JList(listModel);
          list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
          //list.setSelectedIndex(0);
          list.addListSelectionListener(this);
          JScrollPane scrollList = new JScrollPane(list);
          scrollList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scrollList.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollList.setPreferredSize(new Dimension(200,300));
          scrollList.setBorder(
                                        BorderFactory.createCompoundBorder(
                                   BorderFactory.createCompoundBorder(
                    BorderFactory.createTitledBorder("Variables"),
                    BorderFactory.createEmptyBorder(5,5,5,5)),
                                   scrollList.getBorder()));
          //create a pane and put the scroll list and ok/cancel button in it
          JPanel rightPane = new JPanel();
          BoxLayout rightBox = new BoxLayout(rightPane, BoxLayout.Y_AXIS);
          rightPane.setLayout(rightBox);
          rightPane.add(scrollList);
          rightPane.add(controlPane);
          //create a pane and put the scroll text area and arithmetic button in it
          JPanel leftPane = new JPanel();
          BoxLayout leftBox = new BoxLayout(leftPane, BoxLayout.Y_AXIS);
          leftPane.setLayout(leftBox);
          leftPane.add(scrollTextArea);
          leftPane.add(buttonPane);
          //add both pane to the container
          JPanel contentPane = new JPanel();
          BoxLayout box = new BoxLayout(contentPane, BoxLayout.X_AXIS);
          contentPane.setLayout(box);
          contentPane.add(leftPane);
          contentPane.add(rightPane);
setContentPane(contentPane);
     public void valueChanged(ListSelectionEvent e) {
     if (e.getValueIsAdjusting() == false) {
     if (list.getSelectedIndex() == -1) {
          //No selection, disable fire button.
     else {
          //Selection, update text field.
     String name = list.getSelectedValue().toString();
     textArea.append(" " + name + " ");
     public void actionPerformed(ActionEvent e) {
          String cmd = e.getActionCommand();
          if (cmd.equals("Ok")) {
               // save current textarea
               text = textArea.getText();
               System.out.println(text);
               dispose();
               setVisible(false);
          if (cmd.equals("Cancel")) {
               dispose();
               setVisible(false);
          if (cmd.equals("+")) {
               textArea.append(" + ");
          if (cmd.equals("-")) {
               textArea.append(" - ");
          if (cmd.equals("x")) {
               textArea.append(" x ");
          if (cmd.equals("/")) {
               textArea.append(" / ");
          if (cmd.equals("=")) {
               textArea.append(" = ");
          if (cmd.equals("= =")) {
               textArea.append(" == ");
          if (cmd.equals(">")) {
               textArea.append(" > ");
          if (cmd.equals("> =")) {
               textArea.append(" >= ");
          if (cmd.equals("<")) {
               textArea.append(" < ");
          if (cmd.equals("< =")) {
               textArea.append(" <= ");
          if (cmd.equals("! =")) {
               textArea.append(" != ");
          if (cmd.equals("1")) {
               textArea.append("1");
          if (cmd.equals("2")) {
               textArea.append("2");
          if (cmd.equals("3")) {
               textArea.append("3");
          if (cmd.equals("4")) {
               textArea.append("4");
          if (cmd.equals("5")) {
               textArea.append("5");
          if (cmd.equals("6")) {
               textArea.append("6");
          if (cmd.equals("7")) {
               textArea.append("7");
          if (cmd.equals("8")) {
               textArea.append("8");
          if (cmd.equals("9")) {
               textArea.append("9");
          if (cmd.equals("0")) {
               textArea.append("0");
     public static void main(String args []) {
     JFrame frame = new PropertyWindow();
     frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
     System.exit(0);
     frame.pack();
     frame.setVisible(true);
     frame.setResizable(false);
}

If the whole point of the JList is to display the information in the JTextArea and you don't mind losing the selection in the JList I have a solution for you (just had something similar come up).
Add the following lines in the public void valueChanged(ListSelectionEvent e) method:
listModel = list.getModel();
list.setModel(listModel);
This causes the particular animal in the JList to be un-selected and with each subsequent clicks on that JList selection a new ListSelectionEvent will fire and the text will keep appending.
This gives the effect of a JList just being a bunch of buttons that can be clicked on all you want.

Similar Messages

  • Programatically Select an Item in a JList

    Hi,
    I need to do this: Programmatically select an item in a JList.
    JList.selectItem(0) will select the item 0 in the model but it will NOT visually highlight the selected item in the list.
    Neither will ensureIndexIsVisible(0),
    I need to automatically select and item in a list (highlight that item as well)
    As if someone has clicked on that item with the mouse.. however they haven't you see, my program has done it, programatically.
    Please don't refer me to the beginners guide to java, or the API documentation, the answer is not there.
    Thanks

    Swing related questions should be posted in the Swing forum.
    Please don't refer me to the beginners guide to java, or the API documentation, the answer is not there.Yes it is.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

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

  • Problems with the selected item in a JList

    Hi,
    I am using a JList with a JTextPane as renderer, when I select an item in the list the foreground color is black instead of being white and when I go up in the list the foreground color of the items under the selected one is white (they are not visible anymore).
    Does anyone know why this list behaves like that and what I should do to prevent this?
    Thanks in advance
    Here's the code of the renderer (I suppose this is the place where the problems are):
    public class TextPaneListRenderer extends JTextPane implements ListCellRenderer
    public TextPaneListRenderer()
    setOpaque(true);
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
    this.setText(value.toString());
    if (cellHasFocus)
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    else
    setBackground(list.getBackground());
    setForeground(list.getForeground());
    return this;
    getListCellRendererComponent() not yet implemented.");
    }

    Hi,
    i would use isSelected:
    if (isSelected)
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    else
    setBackground(list.getBackground());
    setForeground(list.getForeground());
    It might help, just give it a try.

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

  • 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

  • Getting multiple items from a Jlist

    hi i am trying to get selected items from a Jlist to print out
    but can only seem to get one item at a time using getSelectedValue()
    when i try and use getSelectedValues().toString(); i get
    the following print out [Ljava.lang.Object;@ed783f68 can anyone show me
    where i am going wrong and tell me why i get that print out
    cheers
    submitdetails.addActionListener(
                                                   new ActionListener() {
                                                           public void actionPerformed( ActionEvent e )
                                                      String data = privilegesList.getSelectedValue().toString();
                                                      Object data2 = privilegesList.getSelectedValues().toString();
                                                      System.out.println(data);
                                                      System.out.println(data2);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    The getSelectedValues(...) method returns and ARRAY of OBJECTS. You have to loop through the array to get each object separately:
    Object[] values = privilegesList.getSelectedValues();
    for (int j = 0; j < values.length; j++)
    System.out.println ( values[j].toString() );

  • How to populate table rows with selected listbox items?

    Hello,
    I am trying to populate a table with selected listbox items. Each item should be a new row in the table. The picture below is the listbox and table I am using. I need to get the selected name to populate the Attendee column of the table when the user clicks the Add button. How do you do this with mutltiple attendees selected?
    Thank you,
    Angie

    So you're considering the fact the if the user clicks the button twice, the name will appear twice and you don't want this, right?
    Then you must check if any value is the same than the one you are about to add in the row..
    for (var i = 0 ; i < ListBox1.length; i++){
         if (ListBox1.getItemState(i) == true){
              for (var x = 0 ; x < Table1._Row1.count; x++){
                   var boNewAttendee = true;
                   var strAttendee = Table1.resolveNode("Row1[" + x.toString() + "]").txtAttendee;
                   var newAttendee = ListBox1.getDisplayItem(i);
                   if (strAttendee.rawValue == newAttendee){
                        boNewAttendee = false;
                        break;
              if (boNewAttendee){
                   txtAttendee.rawValue = ListBox1.getDisplayItem(i);

  • IPod Touch Self Selects Menu Items Without Touching Screen - 2nd Gen

    With my iPod Touch sitting flat and motionless on a desk, without even touching it, menu items on the screen are self selecting, as if a ghost were touching the screen and selecting the item. It happens on the lower left portion of the screen on whatever screen is currently displayed. It will continue to select whatever item is in that area of the screen, advancing, or going back, until nothing is in that area of the screen to be selected. This "self Selection" happens at various times, from 1 second to a minute, from when the screen is displayed. Usually at about 5-10 second intervals, but it varies.
    Here is what I have done thus far in attempts to "fix" the problem. None of them have worked and the problem still remains.
    - Restored the iPod from within iTunes (twice)
    - Complete Reset/Erase of the Touch on the unit itself (twice)
    - Ensured the battery was fully charged
    - Synced it with two entirely separate iTunes Libraries on 2 different computers
    - Cleaned the screen VERY well to ensure that no film or residue was on it (it is squeaky clean)
    - Slightly tried to flexed (very gently) the Touch to see if it would change this from happening
    - The shake feature is not the issue (turned off and not touching the iPod Touch)
    - Searched the web pretty thoroughly for answers
    Any thoughts...?
    Message was edited by: Solution Room

    You have the "Halloween Syndrome!!"
    Good news though, it should clear up when Halloween is over with.
    Seriously, it sounds like your screen digitizer needs replacing. Contact a third-party repair service. It will be cheaper to fix that going through Apple.
    Check out the new remodeled MacOSG website! 24-hour Apple-related news & support.
     MacOSG: An Apple User Group  iTunes: MacOSG Podcast  Follow us on Twitter: MacOSG

  • Set Default Value of Multi-select list item

    I have a multi-select list item I want to default the value of to '%' (which is really '%null%') and have it selected. I tried setting default value of item, but it doesn't take '%null%'. I also tried a computation with a static of
    :P507_ITEM := '%null%'; How do you get the default value set and selected?

    Hi
    Shijesh is right, you need to change your null return value and use that return value as your default. Try and use something of the same datatype as your real return values if you plan to use '%' to display all as it will make your queries simpler. eg.
    Company A returns 1
    Company B return 2
    % returns 0
    Then your query would be...
    SELECT ...
    FROM ...
    WHERE company_id = DECODE(:P_COMPANY,1,1,2,2,0,company_id)
    Hope this makes sense.
    Cheers
    Ben

  • Selecting open items in F-03 using additional selections

    I need to select open items in a GL account using more than one additional selection eg. document type, posting date, assignment
    I select Additional Selections then document type then add a document type, then I select Other Selection - posting date and then Process Open Items. Only the first selection for document type is recognised.
    Is this a bug?
    Edited by: Richard Somerset on Jan 7, 2009 5:14 PM

    However SAP help suggest that this can be done
    Searching for Open Items  
    Use
    After you have entered an account with open items, you can search for specific open items to be cleared.
    On the screen for selecting open items, you can search for specific open items to be cleared using the following additional selection fields:
    Gross amount
    Document number
    Posting date
    Other fields depending on the system configuration
    Procedure
    To search for open items using the additional selection criteria, proceed as follows:
    Choose one of these fields, such as Posting date, then choose Execute.
    The screen for entering selection criteria appears.
    Enter one or more single values or ranges within the selection, such as 01/01/1993 through 01/31/1993 for a range of posting dates.
    To search for specific open items by other criteria (optional), choose Edit ® Select more.
    Repeat steps 1 and 2 for the other selection criteria.
    After you enter your selection criteria, you have the following options:
    Display the list of open items by choosing Goto ® Open items.
    Display the clearing document header and the items entered so far by choosing Goto ® Doc. Overview.
    Post the clearing document by choosing Document ® Post
    Edited by: Richard Somerset on Jan 8, 2009 9:05 AM

  • Report for a selection of items+batch numbers that I would have had on hand

    I would like to run a report for a selection of items and batch numbers that I would have had on hand (only) for September 30th.  I have run the batch numbers report but this gives me all transactions from August 1/09 to September 30/09.

    Hi
    If you need to know quantity onhand ,probably you need to run query against OINM tables but If you are lloking for information then I guess this batch and serial number would be handy ....
    Hope this helps
    Bishal

  • Display all valid items and select multiple items

    Let us say I have valid items in table. For each purchase user can select few items from the list. I have to display all valid items from table and user should able to check items to buy. What is the best way we can implement this in forms.
    Thanks, lalitha

    For all the valid items you can create LOV as i understood then user can choose what he wants. But this sentence ti still confusing to me. Or what is the tricky things in you scanerio if only you have to show the valid item then use LOV.
    Lalitk wrote:
    and user should able to check items to buy.-Ammad

  • How to select line items in recording(BDC)

    Hi All,
    we are trying to Recording QP02 transaction ,we have inputs like material,plant,Group,Group Counter.
    after entering these inputs we will get multiful line items(inspection characteristics).we need to check one field for each item.
    How can we get this?
    Please help me?
    Thanks,
    Peddi reddy.

    Hi Kamesh,
    Thanks.
    After selecting line items i am selecting control indicators Tab.
    then Pop up screen called as (Edit characteristic control indicators) will open ,..then just pressing enter..the it will show another pop up ..here i am selecting one field(Long term Inspection)..the process has to do for all line items.
    In My program i have copied BDC performs which i got from Recording.
    Do i need to change tha performs or will it work?
    i tested in foreground with another material .... upto 3 or 4 line items its working fine.after that sytem does.t say anything.
    if i need to chage performs please help me .

Maybe you are looking for

  • Incoming Mac Mail Messages Arrive, then Dissappear

    Have had my iMac for about a month, month and a half. Email has been working fine. Starting yesterday, when I open Mail, I see the new messages coming in at the bottom. By that I mean, the number of messages arriving. I also happens to show 0KB/sec.

  • How can I save song created in GarageBand as a MIDI file

    Is this possible, I'm an old user of Cubase, and before SMPTETrack (someone remembers?) so Midi files are for me an obvious think. In GarageBand a new nice program for begginers and fans of music easily produced I found a little problems finding how

  • Auto brightness- press settings - brightness

    No auto brightness, pressing settings - brightness & wallpaper there is a brightness scroll bar but the box underneath saying auto brightness has gone. It was there before!!! The box was there after updates.

  • ERROR after applying patch CSCtj01051: solaris9 CS 3.3 - LMS 3.2

    I installed a couple of LMS 3.2 point patches on a solaris 9 box. Afterwards the LMS did not started any more. DCRServer hang in "Waiting to initialize" and Apache failed to run. Also a couple of other processes failed (attached pdshow). Troublshooti

  • [SOLVED] Samsung ML-2010R on print server: downgrade CUPS to 1.4.7

    On Mac OSX I have version 1.4.7 and my USB laser printer connected to the router print server works fine. On Arch I have version 1.5.3, same configuration, but the printer doesn't work. I downgraded CUPS to 1.4.7-4 version but now there's a problem w