JComboBox behavior

I'm trying to verify my understanding of the JComboBox behavior. Specifically the events which are generated and when. I have a JComboBox that I reload based on the contents of an "upstream" field. I reload the JComboBox using the focusLost() method of this upstream field. The behavior I see exhibited is that when I add the first item I get an actionPerformed event and an itemStateChanged event (or two) both of which show that the first item in the JComboBox is the selected item. Now, at this time the user has not chosen an item and, actually, I don't even want an item in the combo box portion of the control. After I have loaded the data into the JComboBox I invoke setSelectedIndex(-1) to clear out the JComboBox which again generates an actionPerformed evemt and an itemStateChanged event. Frankly, I'm not interested in reacting to any of the above events during this process. I'm looking for the standard way that people use to avoid reacting to these events. The approach I have taken is to call setEnabled(false) before I manipulate the JComboBox data and call setEnabled(true) when I'm done. Then, in the methods which handle these two events I call isEnabled() and simple return if the JComboBox isn't enabled (obviously, to me at least, if the JComboBox was disabled when this event was generated, it [the event]must have been generated under program control and should be ignored).
Any comments as to the appropriateness of this approach would be appreciated or if I'm missing an elegant solution.
Thank you for your attention to this matter!
Peter

There's not really an elegant solution to your problem.
However, your solution is reasonable but does have some minor flaws.
It assumes that the portion of code responsible for reloading the data can disable the combo box (or combo boxes if the data is shared). Ideally it would simply be the model that gets manipulated; access to the view should be ring-fenced.
The combo box might be disabled for a real reason (like the user can't alter it directly) but its selected item may be changed in another way (eg, the user selects something in another combo box that alters the disabled combo box).
You can simply set a flag somewhere else in your application that indicates whether listeners should take action:
public void itemStateChanged(...)
  if(DataManager.isLoading())
    return;
  /* ... your code here ... */
}This then doesn't hijack the view code to shoehorn in something that's not view-related.
It's certainly not elegant but does provide a clear contract for indicating to your listeners that there's something going on that might influence the action they take.
Another option is to use a ComboBoxModel subclass that is told that it's about to reload and suspends event dispatch until it's told that loading's finished. This is arguably better but does require that you write your own models:
public class MyComboBoxModel implements ComboBoxModel
  private boolean eventsActive;
  public boolean setEventsActive(boolean eventsActive)
    this.eventsActive = eventsActive;
    // If events are reactivated then just pretend that the entire model's changed (for example)!!
    if(eventsActive)
      fireContentsChanged();
      fireSelectedItemChanged();
  protected void fireSelectedItemChanged()
    if(!eventsActive)
      return;
    // loop over listeners, fire item change event
}You get the idea...
Hope this helps.

Similar Messages

  • Extending JComboBox  behavior and changing look and feel

    In order to change JComboBox behavior, usually we will extend the MetalComboBoxUI or WindowsComboBoxUI (for example: for controlling the popup width)
    The problem arise when we want to be able to change the pluggable look and feel: all components got the new look and feel except for the comboboxes.
    A dirty solution can be extending our ComboBoxUI from the new look and feel library but in the case of jgoodies it is even impossible because PlasticComboBoxUI is final
    Any ideas?

    In order to change JComboBox behavior, usually we will extend the MetalComboBoxUI or WindowsComboBoxUI (for example: for controlling the popup width).
    The problem arise when we want to be able to change the pluggable look and feel: all components got the
    new look and feel except for the comboboxes. A dirty solution can be extending our ComboBoxUI from
    the new look and feel library but in the case of jgoodies it is even impossible because PlasticComboBoxUI is final
    My best suggestion: request the L&F provider to make his combo box homogeneous with the other components.

  • Battling JComboBox behavior of removing items

    we are working on a document browser GUI and encountered some weird behavioral issue with JComboBox/DefaultComboBoxModel. The current workaround is ugly and we are wondering if there is somehow different way to get it to work.
    Our application uses an in-house class to keep a list of documents, and this class has APIs for navigation and deletion so forth. On the GUI, we display a JComboBox to show the name of the current document being viewed. This JComboBox is backed by a DefaultComboBoxModel which has a separate list containing only the names of the document. When a user selects a document from the JComboBox, the application jumps to the selected document, and when a user deletes a document, the corresponding document name is removed from the JComboBox.
    The problem is that our in-house class behaves differently than DefaultComboBoxModel. When an item is removed from the in-house class, it points to the next item on the list (i.e. the index value renames the same), unless the last item of the list is removed, and then the index simply points to the new last item of the list. This behavior is intuitive and is in conformation to user requirements.
    However, the DefaultComboBoxModel does the opposite with some oddity. When an item is removed from the ComboModel, the selectedIndex points to the previous item the list (i.e. the index value decrements by 1), unless it is the first item of the list, in which case it behaves even more oddly... it points to the next item in the list, but for some reason, the selectedIndex becomes 1 (instead of 0) as if the item to be deleted is still in the list!
    So we have been having trouble keeping the in-house class and the JComboBox in sync. For one thing, when a user deletes a document, it renders twice for the next document to be viewed (one triggered by JComboBox automatically points to the previous doc, which is incorrect, and the second one is our code that forces JComboBox to select the next doc by setting selected index), and problems occur especially for the boundary cases. We ended up doing a hack - add an ActionListener to the JComboBox only when it receives a mouse-down event and remove the actionListener inside of the actionPerformed() code, so that we can force the JComboBox to display the correct document name without triggering document rendition.
    But this is ugly. We are wondering if there is a better way. One possibility is of course to ditch the defaultComboBoxModel, and implement a mutableComboBoxModel in our in-house class. But is there another way (easier way so we dont have to deal with triggering events etc)? Thanks.

    And the way to solve it with a custom MutableComboBoxModel (also does not auto select an item that is added):
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class ListComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    ListComboBoxModel model = new ListComboBoxModel("one", "two", "three");
                    model.setSelectionChangeOnRemove(SelectionChange.SELECT_NEXT);
                    final JComboBox comboBox = new JComboBox(model);
                    comboBox.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            System.out.println("Selected: "
                                    + comboBox.getSelectedIndex()
                                    + "=" + comboBox.getSelectedItem());
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(comboBox, BorderLayout.PAGE_START);
                    frame.getContentPane().add(
                            new JButton(new AbstractAction("Delete") {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    int index = comboBox.getSelectedIndex();
                                    System.out.println("Before: " + index
                                            + "=" + comboBox.getSelectedItem());
                                    comboBox.removeItemAt(index);
                                    System.out.println("After: "
                                            + comboBox.getSelectedIndex()
                                            + "=" + comboBox.getSelectedItem());
                                    setEnabled(comboBox.getItemCount() > 0);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
        public enum SelectionChange { SELECT_PREVIOUS, SELECT_NEXT, CLEAR_SELECTION }
        private final List<Object> items;
        private SelectionChange changeOnRemove = SELECT_PREVIOUS;
        private Object selected;
        public ListComboBoxModel(Object...items) {
            this.items = new ArrayList<Object>();
            if(items != null) {
                this.items.addAll(Arrays.asList(items));
        public void setSelectionChangeOnRemove(SelectionChange changeOnRemove) {
            if(changeOnRemove == null) {
                throw new NullPointerException("SelectionChange should not be null");
            this.changeOnRemove = changeOnRemove;
        @Override
        public int getSize() {
            return items.size();
        @Override
        public Object getElementAt(int index) {
            return items.get(index);
        @Override
        public void setSelectedItem(Object anItem) {
            if((selected != null && !selected.equals(anItem))
                    || (selected == null && anItem != null)) {
                selected = anItem;
                fireContentsChanged(this, -1, -1);
        @Override
        public Object getSelectedItem() {
            return selected;
        @Override
        public void addElement(Object obj) {
            insertElementAt(obj, items.size());
        @Override
        public void removeElement(Object element) {
            removeElementAt(items.indexOf(element));
        @Override
        public void insertElementAt(Object element, int index) {
            items.add(index, element);
            fireIntervalAdded(this, index, index);
        @Override
        public void removeElementAt(int index) {
            Object removed = items.get(index);
            if(selected != null && selected.equals(removed)) {
                Object newSelection;
                int size = items.size();
                if(size == 1) {
                    newSelection = null;
                else {
                    switch(changeOnRemove) {
                    case CLEAR_SELECTION:
                        newSelection = null;
                        break;
                    case SELECT_NEXT:
                        if(index == size - 1) {
                            newSelection = items.get(index - 1);
                        else {
                            newSelection = items.get(index + 1);
                        break;
                    case SELECT_PREVIOUS:
                        if(index == 0) {
                            newSelection = items.get(index + 1);
                        else {
                            newSelection = items.get(index - 1);
                        break;
                    default:
                        assert false : "Unknown SelectionChange: " + changeOnRemove;
                        newSelection = null;
                        break;
                setSelectedItem(newSelection);
            items.remove(index);
            fireIntervalRemoved(removed, index, index);
    }

  • JComboBox popup list remains open after losing keyboard focus

    Hi,
    I have noticed a strange JComboBox behavior. When you click on the drop down arrow to show the popup list, and then press the Tab key, the keyboard focus moves to the next focusable component, but the popup list remains visible.
    I have included a program that demonstrates the behavior. Run the program, click the drop down arrow, then press the Tab key. The cursor will move into the JTextField but the combo box's popup list is still visible.
    Does anyone know how I can change this???
    Thanks for any help or ideas.
    --Yeath
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Test extends JFrame
       public Test()
          super( "Test Application" );
          this.getContentPane().setLayout( new BorderLayout() );
          Box box = Box.createHorizontalBox();
          this.getContentPane().add( box, BorderLayout.CENTER );
          Vector<String> vector = new Vector<String>();
          vector.add( "Item" );
          vector.add( "Another Item" );
          vector.add( "Yet Another Item" );
          JComboBox jcb = new JComboBox( vector );
          jcb.setEditable( true );
          JTextField jtf = new JTextField( 10 );
          box.add( jcb );
          box.add( jtf );
       public static void main( String[] args )
          Test test = new Test();
          test.pack();
          test.setVisible( true );
          test.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    ran your code on 1.5.0_3, observed problem as stated.
    even though the cursor is merrily blinking in the textfield, you have to click into
    the textfield to dispose the dropdown
    ran your code on 1.4.2_08, no problems at all - tabbing into textfield immediately
    disposed the dropdown
    another example of 'usual' behaviour (involving focus) breaking between 1.4 and 1.5
    the problem is that any workaround now, may itself be broken in future versions

  • JComboBox event notification when select first entry in pop-up menu JDK 6

    I recently began testing a Java GUI, I originally developed with JDK 1.5.0_11, with JDK 1.6.0_3. I have used the JComboBox in several applications developed using JDK 1.3.x and 1.4.x over the years. In every one of these earlier JDKs the JComboBox widgets all behaved the same. When you select the JComboBox widget, the pop-up menu appears and you can select any of the items from the menu list. Having made the selection with either a mouse click or a key press, an event notification is sent. Typically, an ActionEvent as well as either a mouse click event or a keypressed event may be sent. When testing with 1.6.0_x versions of the JDK and JRE, I can't account for any event notification being sent when selecting the first item at the top of the pop-up menu as the initial selection. If I select some other item on the list and then the first item, it works as it is supposed to work, but only after selecting another item first.
    I've placed the JComboBox in a JDialog and a JPanel. There are NO AWT widgets in any containers of the application. The same behavior seems to exist regardless of what other containing Swing component I place the JComboBox in. I'm running these applications on Windows XP, service pack 2. The system is an AMD 64 bit dual processor with 4Gb of RAM. The essential code follows:
    private JComboBox getJcboAlias()
        /* Note here that I am using a defaultComboModel as I have always done */
       jcboAliases = new JComboBox(urls);
       *jcboAliases.setEditable(false);*                               // Note here that the JComboBox is NOT editable
       jcboAliases.addActionListener(new ActionListener()   // ActionListener only receives a notification if the second or
       {                                                                            // another item in the pop-menu list is selected...but never the
          public void actionPerformed(ActionEvent ae)           // first item in the list
             String s = (String) jcboAliases.getSelectedItem();
             for (int i = 0; i < connections.size(); i++)
                conAlias = (String[]) connections.get(i);
                if (s.equals(conAlias))
    isSelected = true;
    break;
    jlblName.setVisible(true);
    jlblAlias.setVisible(true);
    jlblUID.setVisible(true);
    jlblPWD.setVisible(true);
    jtxtName.setText(conAlias[0]);
    jtxtName.setVisible(true);
    jtxtAddress.setText(conAlias[1]);
    jtxtAddress.setVisible(true);
    jtxtUID.setText(conAlias[2]);
    jtxtUID.setVisible(true);
    jtxtPWD.setVisible(true);
    jtxtPWD.setText("");
    jtxtPWD.requestFocus();
    return jcboAliases;
    }    I'm using a non-editable JComboBox because there is a pop-up menu with this and not with the JList widget.  JComboBox behaves more like the JList MicroSoft counterpart.  Another code snippet follows in which the JComboBox is editable.  The same errant behavior occurs when selecting the first item from the pop-up menu: private JComboBox getJcboPCMember()
    jcboPCMember = new JComboBox(PCViewerCustom.getCurrentMembers());
    jcboPCMember.setBounds(250, 103, 180, 20);
    jcboPCMember.setToolTipText("PATHCHECK(ER) member name - Example: CKPPTHCK");
    jcboPCMember.setSelectedIndex(Integer.valueOf(PCViewerCustom.getCurrentHost(3)));
    jcboPCMember.setEditable(true); // Note here that this JComboBox IS editable
    jcboPCMember.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    if (ae.getActionCommand().equals("comboBoxEdited"))
    boolean copy = false;
    for (int i = 0; i < jcboPCMember.getItemCount(); i++)
    if (jcboPCMember.getSelectedItem().equals(jcboPCMember.getItemAt(i)))
    copy = true;
    break;
    if (!copy)
    if (jcboPCMember.getItemCount() > 0)
    if (jcboPCMember.getItemAt(0).equals("No Entries"))
    jcboPCMember.removeItem("");
    jcboPCMember.removeItem("No Entries");
    jcboPCMember.insertItemAt((String) jcboPCMember.getSelectedItem(), 0);
    else
    jcboPCMember.removeItem("");
    jcboPCMember.addItem((String) jcboPCMember.getSelectedItem());
    enableJbtnOK();
    else
    if (jcboPCMember.getSelectedIndex() >= 0)
    PCViewerCustom.setCurrentHost(3, Integer.toString(jcboPCMember.getSelectedIndex()));
    enableJbtnOK();
    else
    JOptionPane.showMessageDialog(null, "Name not selected", "Error", JOptionPane.ERROR_MESSAGE);
    return jcboPCMember;
         I am able to add a new entry to the JComboBox, however, I am still unable to select the first item from the pop-up menu and fire any kind of notification event.  I have not seen this behavior before in any earlier versions of the JDK and it's playing havoc with my ability to deploy the application into a JDK or JRE V6 environment, without adding a bunch of additional code to pre-select the first item on the list, which pretty much defeats the purpose of the JComboBox.  I'll be the first to admit I've done something wrong, but i've built a number of test scenarios now on two systems runing Win XP SP2 and I get the same errant behavior.  I've also added in event listeners for a MouseListerner, a KeyListener and an ItemListener.  Still no event notification on this first item in the list.  Again, however, if I select one of the other items from the pop-up menu list and then select the first item, all is well.  Imagine selling that method of operation to a user....  It occurs to me that this must be a bug in the V6 JComboBox.  I wanted to post this here first, however, in order to determine if this is, in fact, a bug - in other words, am I the only one seeing this, or is this a more widespread issue?  Any assistance in making this determination is greatly appreciated.
    David Baker
    Edited by: Galstuk on Nov 27, 2007 12:21 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    here is the other file as well:
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Attachments:
    VI2.vi ‏5 KB

  • An active component in a JCombobox

    I placed an own component, used to select a date in, a JComboBox, no problem so far. I wrote a simple renderer, place the component on a JPanel � works fine. Now my problem: If I click on the component, the JCombobox closes immediately. No mouse-click reaches the component, the JCombobox swallows the user input, thinks the JPanel was selected and closes the popup window�
    How can I prevent this behavior? The idea is; that a user clicks on the arrow to open the JCombobox ( he could enter the date by hand in the editable JCombobox ), selects a date form the component ( by clicking several buttons ), the date gets show in the JCombobox and clicks again on the arrow to close the JCombobox.
    Thanx for your help!

    The problem is the ListMouseHandler of the BasicComboPopup I think. In order to avoid the closing of the popup, you have to subclass BasicComboPopup and modify the mouseReleased method of its internal class ListMouseHandler.
    Tell me, if you need more info.
    Michael

  • Multiple Linux JComboBox drops in the same position

    Following program create two similar JComboBox dropdown, and in Linux, when it runs, it works weirdly.
    If I first click first dropdown (s1), then later when I click second one (s2), dropdown part still appears under the first component.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JBugClass {
         public static void main(String[] args) {
              JFrame frame = new JFrame("BugClass AWT version");
              Container pane = frame.getContentPane();
              String[] items = { "Item 1", "Item 2", "Item 3" };
              JComboBox s1 = new JComboBox(items);
              JComboBox s2 = new JComboBox(items);
              JButton wx = new JButton("QUIT");
              wx.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.exit(0);
              pane.setLayout(new FlowLayout(FlowLayout.LEFT));
              pane.add(s1);
              pane.add(s2);
              pane.add(wx);
              frame.pack();
              frame.setVisible(true);
    }I created separated string arrays for s1 and s2, but position is still incorrect. It works completely fine in Windows. I am now suspecting that this is a bug of Linux J2SE1.4.0. Does anyone know any workaround?

    All of the features you're asking for are very easy to add and control in LabVIEW once you know what you're looking for. To show the Front Panel of a SubVI, open the VI and navigate to its "Customize Window Appearance" window (this is in File>VI Properties, select Category: Window Appearance, then click "Customize"). Check the "Show Front Panel when called" checkbox.
    However, there are quite a few other properties you'll likely want to edit as well, so it would be best to review the LabVIEW Topic: "Customize Window Appearance Dialog Box".
    In your main VI, put the SubVI in the True case of a Case Structure, then connect your button to the selector terminal. The more complex behavior your asking for can be achieved using multiple case structures.
    Matt Kirk
    Inventor of ImageJVI

  • Problem in JTable with a JComboBox cell editor

    Hi gurus,
    Please help! I am having a problem with a JTable that has a JComboBox cell editor. When the table is first loaded, the combo box column displays correct data. But whenever I click the combo box, the selection will be set to the first item in the combo box list once the popup menu pops up even before I make any new selection. It is very annoying.
    Here is how I set the cell editor:
    populateComboBoxModel(); // populate the combo box model.
    DefaultCellEditor cell_editor = new DefaultCellEditor(new JComboBox(
    combo_model));
    contrib_table.getColumnModel().getColumn(1).setCellEditor(
    cell_editor);
    I didn't set the cell renderer so I assume it is using the default cell renderer.
    Thanks !

    Not quite. The example doesn't have a different cell editor for each row of the table. I'm sure I must be missing something, bc I've found many references to the fact that this is possible to do. And I have most of it working. However, when I click on any given combobox, it automatically switches to the first value in the list, not the selected item. I've tried setting the selected item all over the code, but it has no effect on this behavior. Also, it only happens the first time I select a given cell. For example, suppose the first row has items A, B, and C, with B being the selected value. The table initially displays with B in this cell, but when I click on B, it switches to A when it brings up the list. If I select B, and move on to some other cell, and then go back and click on B again, it doesn't switch to A.
    There seems to be a disconnect between the values that I display initially, and the values that I set as selected in the comboboxes. Either that, or it behaves as though I never set the selected item for the combobox at all.
    Any help would be greatly appreciated.

  • JComboBox refreshing when mouse moves through

    Hello,
    I have JPanel which has a JComboBox with some items in it. If, for example, I select item #3, and then move the mouse up through the comboBox, combobox refreshes, setting the selected item to first again. So the only way for me to avoid resetting the selected item in JComboBox, is to move my mouse through the application making sure to avoid the combobox area (BIG pain). Does anyone know how to avoid this behavior?
    Thank you
    Elana

    Not the combobox popup. The JComboBox is displayed like a drop-down list. After I select a certain item, that item appears as selected. But after I go through that area with a mouse, the selection is reset.
    Elana

  • Wierd JComboBox

    Hello,
    In my application, I open a JComboBox inside a JPanel.
    But the combo box is wierd : the top line is badly drawn. In non editable mode, the current text is drawn, but the arrow is not. In editable mode, nothing is drawn, just a gray line. But the combo box is active : when I click on the top line, the list appears, properly drawn.
    The JPanel is set to opaque. It has a layout manager set to null, and I use setbounds to set the position and size of the combo box. But I have tried also with a layout manager, and the result is the same.
    The paint function of the JPanel draws an image in the back every 1/50 second. I have tried to remove this regular paint, and the result is the same.
    For your information, Labels and ListBox work perfectly in this application.
    I do not understand what is going wrong. Does anyone has an idea?
    Thanks, Francois

    Hello,
    I have made a simple application that deponstrates the problem. Here is the main class :
    * ComboBox problems demonstration
    package combotry;
    import java.awt.*;
    import javax.swing.*;
    public class Main
        JFrame window;
        CPanel panel;
        JComboBox combo;
        public Main()
        public void run()
         // Creates a JFrame without layout manager
         window = new JFrame() ;
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.getContentPane().setLayout(null);
         // Creates panel
         panel=new CPanel();
         panel.setPreferredSize(new Dimension(640, 480));
         panel.setLayout(null);
         window.getContentPane().add(panel);
         panel.setOpaque(true);
         // Position window and panel
         window.setVisible(true);
         Insets insets=window.getInsets();
         int width=640+insets.left+insets.right;
         int height=480+insets.top+insets.bottom;
         window.setSize(width, height);
         panel.setBounds(0, 0, 640, 480);
         // Creates combobox
         String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
         combo=new JComboBox(petStrings);
         combo.setSelectedIndex(4);
         Dimension d=combo.getPreferredSize();
         combo.setEditable(true);
         combo.setVisible(true);     
         panel.add(combo);
         combo.setBounds(100, 100, 250, d.height);
            // Main loop
         do
             try
              Thread t=Thread.currentThread();
              t.sleep(20);
             catch(InterruptedException e)
         }while(true);     
        public static void main(String[] args)
         new Main().run();
    }And here is the Panel class :
    * CPanel.java
    package combotry;
    import javax.swing.*;
    import java.awt.*;
    public class CPanel extends JPanel
        public CPanel()
        protected void paintComponent(Graphics g)
         Graphics2D g2=(Graphics2D)g;
         Color c=new Color(0xFFFFFF);
         g2.setColor(c);
         g2.fillRect(0, 0, 640, 480);          
    }If you run this application, you will see that the combo box top line is gray. When you click on it, the list opens. But no arrow, just a gray line. Same behavior (a little better) if you set editable to false.
    Any idea anyone?

  • Activating A JComboBox used as a TableCellRender

    In my table there are some columns where a cell can contain multiple rows, so I have created by own CellRenderer which subclasses JPanel and contains a JComboBox showing the first value. (I dont subclass JComboBox directly because there are other things I need to display in the renderer which I wont go into here )
    This works fine but clicking on the combo drop down button doesnt do anything.
    I think this is because the combo box isnt getting the click, its just going to the JPanel or the cell but I cant work how to get it. Could anyone help please ?

    Remember that the whole idea behind the table cell renderer is that you are not actually putting the RenderComponent inside of the table cell, it is just painting what the component looks like in the cell... So there is to way to interact with that component, sinse it isn't really there.
    The only way to give the illusion of this is use TableCellEditors. You can modify the TableCellEditors behavior to activate only on a single click if you want, you can even return the same
    Component in the Editor as you do in the Renderer.
    Does this help?
    Josh Castagno
    http://www.jdc-software.com

  • How to cause JComboBox to open to preselected item?

    If you initialize a JComboBox to an item (using setSelectedIndex, for instance), the first time that the comboBox is opened, it will open at the top of the list, not at the selected item. For example:
    JComboBox jComboBoxHourPicker = new JComboBox();
    // Add comboBox items here
    jComboBoxHourPicker.setSelectedIndex(22);
    The comboBox will correctly show the 23rd item selected. When the user opens the comboBox, however, it will open at the first item, not at the 23rd. If the user closes the comboBox without changing the selection, though, the next time that the comboBox is opened it will have scrolled to the selected item.
    The JList class has the ensureIndexIsVisible() method. Does anyone know how to get the same behavior for the JComboBox class?

    This is a known bug that has been fixed in v1.4. Check out the thread below, by me, for all the details. You're following in my footsteps.
    If you need a workaround for 1.3, follow the link into the bug database and there's a pretty decent one there.
    http://developer.java.sun.com/developer/bugParade/bugs/4337516.html

  • Bug when using JComboBox as JTable CellEditor

    Hello! I have a JTable that displays database information, and one of the columns is editable using a JComboBox. When the user selects an item from the JComboBox, the database (and consequently the JTable) is updated with the new value.
    Everything works fine except for a serious and subtle bug. To explain what happens, here is an example. If Row 1 has the value "ABC" and the user selects the editable column on that row, the JComboBox drops down with the existing value "ABC" already selected (this is the default behavior, not something I implemented). Now, if the user does not select a new value from the JComboBox, and instead selects the editable column on Row 2 that contains "XYZ", Row 1 gets updated to contain "XYZ"!
    The reason that is happening is because I'm updating the database by responding to the ActionListener.actionPerformed event in the JComboBox, and when a new row is selected, the actionPerformed event gets fired BEFORE the JTable's selected row index gets updated. So the old row gets updated with the new row's information, even though the user never actually selected a new item in the JComboBox.
    If I use ItemListener.itemStateChanged instead, I get the same results. If I use MouseListener.mousePressed/Released I get no events at all for the JComboBox list selection. If anyone else has encountered this problem and found a workaround, I would very much appreciate knowing what you did. Here are the relavent code snippets:
    // In the dialog containing JTable:
    JComboBox cboRouteType = new JComboBox(new String[]{"ABC", "XYZ"));
    cboRouteType.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ev) {
              doCboRouteTypeSelect((String)cboRouteType.getSelectedItem());
    private void doCboRouteTypeSelect(String selItem) {
         final RouteEntry selRoute = tblRoutes.getSelectedRoute();
         if (selRoute == null) { return; }
         RouteType newType = RouteType.fromString(selItem);
         // Only update the database if the value was actually changed.
         if (selRoute.getRouteType() == newType) { return; }
         RouteType oldType = selRoute.getRouteType();
         selRoute.setRouteType(newType);
         // (update the db below)
    // In the JTable:
    public RouteEntry getSelectedRoute() {
         int selIndx = getSelectedRow();
         if (selIndx < 0) return null;
         return model.getRouteAt(selIndx);
    // In the TableModel:
    private Vector<RouteEntry> vRoutes = new Vector<RouteEntry>();
    public RouteEntry getRouteAt(int indx) { return vRoutes.get(indx); }

    Update: I was able to resolve this issue. In case anyone is curious, the problem was caused by using the actionPerformed method in the first place. Apparently when the JComboBox is used as a table cell editor, it calls setValueAt on my table model and that's where I'm supposed to respond to the selection.
    Obviously the table itself shouldn't be responsible for database updates, so I had to create a CellEditListener interface and implement it from the class that actually does the DB update in a thread and is capable of reporting SQL exceptions to the user. All that work just to let the user update the table/database with a dropdown. Sheesh!

  • Transfer of the variable through JComboBox

    Hello people,
    I have the following question. In the main JFrame class i put on the JPanel JComboBox. Depending on the values i choose with the help of JCombobox, my following program shoud change the behavior, then in one of classes which is called from another class i use the chosen value.
    so, should i again call main class in one of subclasses with the aim to transfer of the given value.? When i call the main the program was hanging,
    Thank you in advance
    GJavagirl

    My
    AnimatorFrame.class calls 2 classes
    Animator11 and Animator33
    Animator33 calls ReadFile.class, but the value (the name of the file is defined in the AnimatorFrame ,
    i see only one way to call Animator33(filename), which calles the ReadFile(filename)
    Finally my main program doesn't work, what wrong with it?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class AnimatorFrame extends JFrame implements ActionListener
         Animator11 an1;
         Animator33 an3;
           JButton okbutton,endbutton;
            JPanel buttonPanel;
         public AnimatorFrame() {
              super("Animator");
              addWindowListener(new WindowDestroyer());
              createComponents();
              pack();
              setVisible(true);
         private void createComponents() {
              Container c=getContentPane();
                    buttonPanel=new JPanel();
                    okbutton=new JButton("Start");
                    endbutton=new JButton("Stop");
              buttonPanel.add(okbutton,BorderLayout.CENTER);
                    buttonPanel.add(endbutton,BorderLayout.CENTER);
                    an1=new Animator11();
              an3=new Animator33();
              an1.setLayout(new BorderLayout());
              an1.add(an3, BorderLayout.NORTH);
                    an1.add(buttonPanel,BorderLayout.CENTER); 
              c.add(an1, BorderLayout.SOUTH);
         public void startAnimation() {
              an1.start();
              an3.start();
             public void actionPerforme(ActionEvent e)
       if(e.getActionCommand().equals("Start"))
          this.startAnimation();
       if(e.getActionCommand().equals("Stop"))
        System.exit(0);
         public static void main(String[] args) {
              AnimatorFrame f=new AnimatorFrame();
                    f.createComponents();
                    f.setVisible(true);
    //          f.startAnimation();
    }It gives animator class must be declared abstract!
    i didn't present here ComboBox problem......

  • JComboBox scroll bar thumb does not move

    I have an application that is using a third-party panel class that extends JPanel. For some reason my JComboBox scroll bar thumbs do not move unless the pop-up menu viewport extends outside the frame boundary. Does anyone have any idea what might be causing this or have any suggestions on how I might trouble shoot the problem? I would appreciate any feedback, thanks.

    Arrgh, I first reported this behavior (well, alright, I was using a table control/indicator, not the MCL) back in LabVIEW 8.0.  The discussion thread can be found on the LAVA forums, starting September 14, 2006.  In that discussion, Scott Menjoulet and jhoskins seemed to be able to work around it with the "custom control in a project fix", but I could never get that to work, at least not when I built the custom table into an executable.  I filed a bug report on the next beta cycle, but I can't find my old bug reports/CARs online anymore.
    But I'm reasonably certain it's been an identified bug since 8.5.
    Dave
    David Boyd
    Sr. Test Engineer
    Philips Respironics
    Certified LabVIEW Developer

Maybe you are looking for

  • How to write or paste words with cyrillic font

    Hi all, I am having a difficulty in write and paste words with cyrillic (russian) font. currently, I am using acrobat 7 standard and windows 7 professional 64 bit. anyone can help me out? thanks.

  • *** iTunes!!?? Library erases after closing window...

    Question for anyone who knows, or may have had the same problem.. I just bought an iphone, installed iTunes 8 on my laptop. I imported all the music from my computer into iTunes, (over 2,000 songs) synced my iphone, closed iTunes. The next day I turn

  • Do we need to install the data host proxy on the SUN server?

    Hi folks, Hopefully somebody can help me out here as I'm new to sun storage. Basically we have one 6140 arrays attached to Solaris servers. We have installed the CAM software on a CentOS system and connected to the array. We also created the VOLUMEs.

  • DMA Error in Acquisition of Image from 1473R

    Hiii... I am using Frame Grabber NI PCIe-1473R to acquire images from a dragster camera over CamLink interface. I am using "1-Tap 10-Bit Camera with Frame Trigger" example code to acquire images. When I am running the above example code to acquire th

  • Can AE view frame 1 and frame 20 at the same time?

    Hi all, Is there any way to view ,for example, frame 1 on the left view, and frame 20 on the right view? I tried "Locking"  the view in COMP A and look at COMP B. Although you CAN look at two different images (left & right views) you can ONLY view 2