Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / May 2007

Tip: Looking for answers? Try searching our database.

JComboBox.setSelectedItem() doesn´t update selected Item?

Thread view: 
Piet71 - 25 May 2007 22:24 GMT
Hi,
I have written a program that heavily uses JComboBoxes to have the
user select some stuff. In oder to allow for a quick exchange between
JComboBox and JList, I have coded a class that could serve as Model
for both JComponents.  In my program it is frequently the case that
when the user selects an item from a JComboBox, the selection in other
JComboBoxes needs to be updated and the new selection shown in the
JTextField of the JComboBox. The latter is not working. Only when you
click on the JComboBox is the entry updated, though in the drop down
box, the correct item was already selected. Here is some sample code.
Is there something wrong with my CombinedListModel class?
Many thanks in advance!
Regards, Piet
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class ComboProblemDemo extends JFrame implements
ActionListener{
    JComboBox fruit;
    JComboBox basket;
    ArrayList<Fruit> fruitlist = new ArrayList<Fruit>();
    ArrayList<Basket> basketlist = new ArrayList<Basket>();
    CombinedListModel fruitModel;
    CombinedListModel basketModel;
    public static void main(String[] args){
        ComboProblemDemo cpd = new ComboProblemDemo("Combo Problem Demo");
        cpd.pack();
        cpd.setVisible(true);
    }
    public ComboProblemDemo(String title){
        super(title);
        fruitModel = new CombinedListModel();
        basketModel = new CombinedListModel();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        fruit = new JComboBox(fruitModel);
        fruit.addActionListener(this);
        basket = new JComboBox(basketModel);
        for(int b = 0;b<2;b++){
            basketlist.add(new Basket(b));
        }

        for(int f = 0;f<2;f++){
            Fruit fr = new Fruit(f);
            fruitlist.add(fr);
            fr.setBasket(basketlist.get(0));
        }

        for(int f = 3;f<5;f++){
            Fruit fr = new Fruit(f);
            fruitlist.add(fr);
            fr.setBasket(basketlist.get(1));
        }
        fruitModel.setItems(fruitlist);
        basketModel.setItems(basketlist);
        panel.add(fruit);
        panel.add(basket);
        setContentPane(panel);
    }
    public void actionPerformed(ActionEvent ae){
   
basketModel.setSelectedItem(((Fruit)fruit.getSelectedItem()).getBasket());
    }
}
class Fruit{
    private int index;
    private Basket basket;
    public Fruit(int index){
        this.index = index;
    }
    public String toString(){
        return "Fruit "+index;
    }
    public Basket getBasket(){
        return this.basket;
    }
    public void setBasket(Basket basket){
        this.basket = basket;
    }
}
class Basket{
    private int index;
    public Basket(int index){
        this.index = index;
    }
    public String toString(){
        return "Basket "+index;
    }
}
class CombinedListModel extends AbstractListModel implements
ComboBoxModel,ListSelectionListener{
    private java.util.List<? extends Object> items = new
ArrayList<Object>();
    private Object selected = null;
    public CombinedListModel(){
    }
    public void valueChanged(ListSelectionEvent lse){
        System.out.println("value changed, index is "+lse.getFirstIndex()+"
is adjusting:"+lse.getValueIsAdjusting() );
        //if (lse.getValueIsAdjusting()){
            //selected = this.items.get(lse.getLastIndex());
        selected = ((JList)lse.getSource()).getSelectedValue();
        //}
        //setSelectedItem(lse.getSource().);
    }
    public void setItems(java.util.List<? extends Object> items){
        this.items = items;
        if (items.size() > 0) selected = this.items.get(0);
        fireContentsChanged(this,0,getSize());
    }
    public Object getElementAt(int index){
        return items.get(index);
    }
    public int getSize(){
        int size = items == null ? 0 : items.size();
        return size;
    }
    public void setSelectedItem(Object item){
        System.out.println("Selection changed");
        if(items.contains(item)){
            selected =item;
        }
        else{
            System.out.println("Selection not possible");
        }
    }
    public Object getSelectedItem(){
        return selected;
    }
    public void clear(){
        this.items.clear();
        fireContentsChanged(this,0,this.items.size()-1);
    }
}
Piet71 - 25 May 2007 22:27 GMT
Sorry, I just figured out that the title " JComboBox.setSelectedItem()
doesn?t display selected Item?" would have been more appropriate.
Roedy Green - 25 May 2007 22:36 GMT
>basket = new JComboBox(basketModel);
>        for(int b = 0;b<2;b++){
>            basketlist.add(new Basket(b));
>        }

You hard coding lengths, a big naughty.  See
http://mindprod.com/jgloss/jcombobox.html
for how to do this.

Normally you add Strings rather than objects to the JComboBox.

You have so much extra stuff beyond the JComboBox that might not be
working. Get your code working with Strings. Then if you must use
objects, make sure they have a toString method, and add a couple
manually.  Then do your fiddling with ArrayLists and combining.

The way it is, you can't tell if you problem is with JComboBox or with
your ArrayLists and objects.
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Piet71 - 26 May 2007 07:46 GMT
Thanks for your comments, Roedy.
> The way it is, you can't tell if you problem is with JComboBox or with
> your ArrayLists and objects.
In my real program I have added lots of System.out.println's from
which I could tell that everything was working as expected and that
the selected object was updated except that the new selected object
was not shown in the JComboBox.
I have found out in the meantime that I simply need to fire an event
in my setSelectedItem method of the CombinedListModel class . Makes
sense that the JComboBox will not update its view when the
setSelectedItem method is invoked by bypassing the JComboBox. Here is
the new version. It seems to be working but is not throughly tested.
To do the testing I will have to remove that changes that I made
yesterday when desperately looking for the source of the unexpected
behaviour.
<code>
public void setSelectedItem(Object item){
   System.out.println("Selection changed");
   if(items.contains(item)){
       selected =item;

fireContentsChanged(this,items.indexOf(item),items.indexOf(item));
   }
   else{
       System.out.println("Selection not possible");
   }
}
</code>
Regards
Piet
Lew - 26 May 2007 15:31 GMT
> In my real program I have added lots of System.out.println's from

One trouble with System.out.println (why didn't you use System.err?) is that
they have to be removed for production.  There are many reasons not to use
System.out for debug or trace purposes.

Why not using logging?

Signature

Lew

RedGrittyBrick - 26 May 2007 17:16 GMT
>> In my real program I have added lots of System.out.println's from
>
> One trouble with System.out.println (why didn't you use System.err?) is
> that they have to be removed for production.

Sorry to jump in here, I'd certainly agree that you should remove those
sort of statements (or make them conditional), however since output to
System.out is not normally visible in a jar'd Swing application (i.e.
when not run from an IDE or command shell) - is there any major problem
if they're left in?

> There are many reasons not
> to use System.out for debug or trace purposes.

I'd be interested in reading your list of those reasons.

> Why not using logging?

I can't answer for the OP, but in my case it went like this:

- System.out.println() works
  - it needs no special classes/jars bundled with your app.
  - it needs no complex XML config files
  - it needs no class instantiation/initialisation
  - it is just as easy to make conditional
  - it is just as easy to comment-out or remove using search/replace

- Logging classes seem like they're oriented to making complex
  logging needs possible. Few of them make simple jobs simple.

- There's too many to choose from. Writing System.out.println()
  a few dozen times takes a lot less gumption than studying a
  half dozen logging classes and choosing one then using it.

For my limited needs I preferred to reinvent the logging wheel myself,
though I did feel properly guilty about it :-) I ended up with something
I could control by environment variables or command line params, which
could be used statically without configuration files or instantiation,
which could have logging levels set programatically if needed, and which
did the right thing in the absence of any configuration.

It goes without saying that it does a lot less than the more developed
logging classes. But I like that it's as easy to use as
System.out.println().

I still use System.out.println() for simple programs.

I'm open to persuasion, so I'm interested to hear more details of the
evils of System.out.println().
Lew - 27 May 2007 23:53 GMT
>>> In my real program I have added lots of System.out.println's from
>>
[quoted text clipped - 6 lines]
> when not run from an IDE or command shell) - is there any major problem
> if they're left in?

Only the drag on performance - println() is invoked regardless of need.
Logging libraries are optimized for minimal impact on production performance.

>> There are many reasons not to use System.out for debug or trace purposes.
>
> I'd be interested in reading your list of those reasons.

The performance reason, ibid.  Not having the output stream cluttered with
trace statements.

>> Why not using logging?
>
> I can't answer for the OP, but in my case it went like this:
>
> - System.out.println() works
>   - it needs no special classes/jars bundled with your app.

Specious.

>   - it needs no complex XML config files

Neither does log4j.

>   - it needs no class instantiation/initialisation

Neither does log4j unless you need the flexibility.

>   - it is just as easy to make conditional

No, it isn't.  The conditions add complexity to your code, instead of being
hidden inside the logging aspect.

>   - it is just as easy to comment-out or remove using search/replace

Which is a source code change, much harder than not changing source code.
Logging wins, since it doesn't need any code change, not commenting out nor
removal via search/replace.

> - Logging classes seem like they're oriented to making complex
>   logging needs possible. Few of them make simple jobs simple.

I have no idea how you came up with this.  Logging libraries are dog-simple to
use, about as complex as:

Logger logger = Logger.getLogger( getClass() );
...
logger.error( msg );

> - There's too many to choose from. Writing System.out.println()
>   a few dozen times takes a lot less gumption than studying a
>   half dozen logging classes and choosing one then using it.

I cannot believe you are touting ignorance as an excuse.  Pathetic.

Logging takes all of five minutes to learn.  Arguing that you are too lazy to
learn it is not an indictment of the logging library but of the practitioner.

> For my limited needs I preferred to reinvent the logging wheel myself,
> though I did feel properly guilty about it :-) I ended up with something
> I could control by environment variables or command line params, which
> could be used statically without configuration files or instantiation,
> which could have logging levels set programatically if needed, and which
> did the right thing in the absence of any configuration.

I don't see how any of that differs from, say, log4j.

> It goes without saying that it does a lot less than the more developed
> logging classes. But I like that it's as easy to use as
> System.out.println().

I like logging, which is as easy to use as "logger.error( msg )" and doesn't
require re-compilation to remove them,

> I still use System.out.println() for simple programs.
>
> I'm open to persuasion, so I'm interested to hear more details of the
> evils of System.out.println().

Go to, say, the Apache logging page for that.  They lay the argument out
better than I can.

You should actually learn to use, say, log4j, before you pass judgment.  By
admitting that you haven't learned either that nor java.util.logging, you
admit that you do not have a basis for your judgment.

Try it, you'll like it.

Signature

Lew

RedGrittyBrick - 28 May 2007 21:37 GMT
>> - System.out.println() works
>>   - it needs no special classes/jars bundled with your app.
>
> Specious.

>>   - it needs no class instantiation/initialisation
>
> Neither does log4j unless you need the flexibility.

All the examples I've seen seem to involve something like
`static Logger logger = Logger.getLogger(test.class);`

>> - Logging classes seem like they're oriented to making complex
>>   logging needs possible. Few of them make simple jobs simple.
[quoted text clipped - 5 lines]
> ...
> logger.error( msg );

Can you just invoke methods statically like
   Logger.error(msg);

>> - There's too many to choose from. Writing System.out.println()
>>   a few dozen times takes a lot less gumption than studying a
>>   half dozen logging classes and choosing one then using it.
>
> I cannot believe you are touting ignorance as an excuse.

I didn't think I was :-)

Actually its a problem I've encountered more than once with Java. A
recent example: I have a web-service written in Perl and wanted to test
access to the service from Perl, C# and Java. I'd a little experience of
Perl and Java but none of C#.

With Perl, THE way to do web services is to use SOAP::Lite. No need to
research lots of options. A SOAP::Lite test client can be written in
under a dozen lines of code.

With C#, I'd not written a line of C# before, but I downloaded Mono,
read http://www.mono-project.com/Web_Services, wrote a dozen lines of C#
and typed four commands and had a working client within an hour. I
didn't have to research several toolkits and choose one.

With Java I've spent hours Googling and reading reviews and tutorials
for what seemed like dozens of web-services toolkits. Most of it seemed
ten times as much work as Perl or C#. It was hard to work out what was
obsolete stuff and what was 'standard' for Java 6. I downloaded the
latest Eclipse Web-Tools Platform and tried to generate a stub class
from the WSDL but had problems. In the end I used the rather nasty
approach suggested in
http://www.ibm.com/developerworks/xml/library/x-soapcl/ which I
supplemented with a SAX parser, simply in order to avoid spending too
much time learning something which was somewhat peripheral to the project.

> Pathetic.

Cruel bastard ;-)

> Logging takes all of five minutes to learn.  

I spent hours trying to find out what logging classes were available,
which were widely used and whether any were a standard part of JRE 1.5.

> You should actually learn to use, say, log4j, before you pass judgment.  
> By admitting that you haven't learned either that nor java.util.logging,
> you admit that you do not have a basis for your judgment.
>
> Try it, you'll like it.

I will try it, but I suspect I'll probably still use
System.out.println() in small programs (one or two classes, < 200 LOC).

Appendix A:

Complete Perl web-services client

  #!perl
  use strict;
  use warnings;
  use SOAP::Lite;
  print SOAP::Lite
    ->proxy('http://example.com/service')
    ->uri('Widgets')
    ->getWidgetDescription('Foo');

Complete C# web-services client (excluding stub generated from WSDL)

  using System;
  class GetWidgetDescription {
      public static void Main(string [] args) {
          WidgetService service = new WidgetService();
          Console.WriteLine(service.getWidgetDescription("Foo"));
      }
  }

My real service returned arrays of objects but that didn't add
significantly to the time taken to produce working Perl or C# clients
with which to test the service.

Doubtless a Java client *can* be just as concise and easy to learn but
the above were almost straight from the first tutorials I found. I've
not found a simple Java tutorial that only uses classes that are part of
the standard JRE.
Lew - 29 May 2007 02:12 GMT
Lew wrote:
>> Pathetic.

> Cruel bastard ;-)

Sorry.  Intended only for rhetorical effect.  All feelings hurt in this
newsgroup are the sole responsibility of the reader, blah blah blah.

>> Logging takes all of five minutes to learn.  

> I spent hours trying to find out what logging classes were available,
> which were widely used and whether any were a standard part of JRE 1.5.

Actually, this is a common problem with Java, all right.  I found that log4j
was very simple, adapted well to learning a little at a time, and relieved me
of all worries about re-instrumenting for production.  I therefore ignored all
the other choices.

>> You should actually learn to use, say, log4j, before you pass
>> judgment.  Try it, you'll like it.

> I will try it, but I suspect I'll probably still use
> System.out.println() in small programs (one or two classes, < 200 LOC).

Or maybe you won't like it.  It took me a few projects to even bother to set
up a log4j.properties for a project.  Its simplest uses did enough for a
while, at least as much as println() and with much less footprint.

> Doubtless a Java client *can* be just as concise and easy to learn but
> the above were almost straight from the first tutorials I found. I've
> not found a simple Java tutorial that only uses classes that are part of
> the standard JRE.

It's a fair cop.  Java can be a real beast.

Signature

Lew

Andrew Thompson - 26 May 2007 09:45 GMT
>Hi,
>I have written a program that heavily uses JComboBoxes to have the
[quoted text clipped - 4 lines]
>JComboBoxes needs to be updated and the new selection shown in the
>JTextField of the JComboBox. The latter is not working.

I am not entirely confident I understand the code, but
try changing this bit for different behaviour.

>public class ComboProblemDemo extends JFrame implements
>ActionListener{
...

>    public void actionPerformed(ActionEvent ae){
>   
>basketModel.setSelectedItem(((Fruit)fruit.getSelectedItem()).getBasket());

 // tell the UI to update..
 repaint();

>    }
....

HTH

Signature

Andrew Thompson
http://www.athompson.info/andrew/

Piet71 - 28 May 2007 16:14 GMT
> >Hi,
> >I have written a program that heavily uses JComboBoxes to have the
[quoted text clipped - 19 lines]
>   // tell the UI to update..
>   repaint();
Thanks for the idea. I haven´t tried it yet, since the problem went
away by firing a suitable event in the model class that apparently
told the view (the JComboBox) to repaint. In this way, all JComboBoxes
that get their data from the CombinedListModel class should
automatically show the right behaviour w/o the need to repaint() all
of them. BTW, DefaultComboBoxModel also calls
fireContentsChanged(this,-1,-1) in its implementation of
setSelectedItem(Object o). I have changed my implementation
accordingly. However, I was unable to find when this event finally has
an effect in the JComboBox.
JComboBox implements ListDataListener and registers itself as such on
the ComboBox model in the JComboBox.setModel(ComboBoxModel aModel)
method. Thus, the JComboBox's contentsChanged method is invoked when
fireContentsChanged() is invoked in the model. The contentsChanged()
method calls protected selectedItemChanged() of JComboBox if the new
and old selection differ, and selectedItemChanged() then invokes
fireItemStateChanged() which then calls itemStateChanged() on every
registered ItemListener of the JComboBox and that seems to be the end
of the chain. I checked whether JComboBox registers itself as an
ItemListener on itself, but that doesn´t seem to be the case.
@Lew: Thanks for your hints regarding logging. I will have definitely
a look at log4j because I am reaching the limits of
"System.out.println()" debugging. But for my last problem, System.out
seemed to be the faster solution.
Regards, Piet


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.