Interesting Focus II: JComboBox, 2 JLists and 1 Button

Hi All,
Another Interesting Keyboard Focus Question:
What we want to do?
Let's say we want to build a JComboBox whose popup contains 2 JLists and a button.
What we would probably want to do is:
comboBox.setUI(new MyComboBoxUI());
MyComboBoxUI will extend BasicComboBoxUI and
ovveride createPopup to return a BasicComboPopup subclass
which will add the other JList and JButton.
(One can argue that this is not a JComboBox anymore, but bare with me)
Does it work?
This will work great with the Mouse, but with the Keyboard we face a problem:
After our popup is displayed, The JComboBox Still Has The Focus - Any UP or DOWN Events are really proccessed by the JComboBox which simulates JList navigation...
This is happening because the popup is not keyboard-focusable (and so do all of its components)
Where' s the problem?
We want to be able to:
1. Press TAB to navigate thru the 3 components
2. Press UP and DOWN to navigate the two JLists
3. Press Space to activate the JButton
Possible solutions:
1.
Don't subclass BasicComboPopup and write a ComboPopup which uses a Focusable JWindow.
Problem: The JComboBox will lose the focus when the popup opens
2.
Simulate all the DOWN/UP/TAB/SPACE events to the popup
Problem: The components are not focusable, hence there is no indication
of who is the current focused component
(Might be solved by surrounding the 'focused' component with a border)
Your thoughts?
If you haven't fell asleep by now, you are welcomed to share you ideas, Thanks
Eyal Katz

Sorry, I don't understand what you are trying to accomplish. However one line did catch my eye.
This is happening because the popup is not keyboard-focusable The code in the popupPopup() method in the following post might help:
http://forum.java.sun.com/thread.jspa?threadID=636842

Similar Messages

  • Holding Focus on JCombobox

    Actually I am adding FocusListener in the JTextfield of the JComboBox .In the focus lost event I am holding the focus of the textfield of the combobox unless a condition(i am not explaning right now) fulfills.works fine if TAB key is pressed but when i shift focus to a button then i am able to come out and press the button, which i do not want.

    And what do I have to do with that? I don't know. What are you trying to do?
    I was assuming that you where adding a FocusListener to the combo box, but you never received a focusGained event. Well thats because the combo box doesn't receive focus. It is a compound component consisting of an editor component and a button component. The editor component receives focus, so if you want to trap a focus event you need to add the FocusListener to the editor component.

  • How many itens can I put inside a JComboBox or JList?

    How many itens can I put inside a JComboBox or JList?
    Thanks
    Renato de Melo

    Lots. I have put 10,000 in one, for example. !!! ComboBox with 10,000 items how did you solved
    scrolling slow down problem in ComboBox.
    I'm trying for weeks to speed up JComboBox
    what I did was
    1) I've created custom model with sorted
    items and I'm using binarySearch for getting and setting
    items in model this greatly improved performance
    2) I'm using setPrototypeDisplayValue(Object obj)
    function
    but still scrolling with arrow keys and PgUp,PgDown
    is too slow especialy in the end of the list.
    Any ideas ?

  • JComboBox or JList with SQL queries. Best practises.

    Hi!
    I'm wondering what you do in the following situation, providing you develop a hotel reservation application and you have a form where you enter room details: room number, number of rooms, description and type (JComboBox).
    So when executing an INSERT query what do you usually do? Do you store ID's of types or execute addtion SELECT query to get the if of the selected type?

    Thank you very much! I like your approach, but what if I should fill in a form automatically? I mean I have a section in my application where you can edit rooms, you choose a room from a JList and fter clicking on a particular room, the fields of the form get entered and if I have a JComboBox there what should I do?
    I use this approach:
    <code>
    public void valueChanged ( ListSelectionEvent e )
    Item item = ( Item ) lRooms.getSelectedValue();
    try {
    Db db = new Db ();
    ResultSet rs = db.executeQuery ( "SELECT * FROM rooms " +
    "WHERE id = " + item.getId () );
    rs.next ();
    pRoomsEdit.this.id = rs.getInt ( "id" );
    tfNo.setText ( item.getName () );
    ComboBoxModel cbm = cbType.getModel ();
    ResultSet rsType = db.executeQuery ( "SELECT name FROM types " +
    "WHERE id = " + rs.getString ( "type" ) );
    rsType.next ();
    cbm.setSelectedItem ( new Item ( rs.getInt ( "id" ), rsType.getString ( "name" ) ) );
    tfRoomNum.setText ( rs.getString ( "roomNum" ) );
    taDesc.setText ( rs.getString ( "description" ) );
    catch ( SQLException se ) {
    se.printStackTrace ();
    </code>

  • On our project site, with Firefox 4 and 5, buttons don't take the keyboard focus if you mouse-click on them. Is this a problem of our site?

    On a page like http://www.ori.uzh.ch/links.html, clicking a link opens a new tab, and after closing that tab, you can move to the next link with the tabulator key. On that site, it still works with Firefox 5. I also worked on our project site (password secured, sorry) with Firefox up to 3.6.18. But now, if I open a link with the mouse, close that tab again and press the tab key, the focus just goes to the first clickable button, as if I had not clicked any button previously. If I open a link by tab key and "enter", the keyboard focus is preserved on that button. But there are many many buttons on our pages, and they reload frequently.
    BTW I adjusted the system preferences, so that the keyboard focus moves between all controls. (see http://www.tipstrs.com/tip/1505/Tab-key-to-select-form-elements-in-Firefox-on-the-Mac). But I don't think the problem is related to that.

    I found out that our buttons are no links, but input tags, type="submit". I'll discuss the problem with our programmer.

  • I am interested in purchasing a new PC and wanted to transfer all of the music on my Itunes onto my new computer's Itunes the easiest was possible. Any suggestions?

    I am interested in purchasing a new PC and wanted to transfer all of the music on my Itunes onto my new computer's Itunes the easiest was possible. Any suggestions?

    These are two possible approaches that should work to move the existing library to the new laptop.
    Method 1
    Backup the library with this User Tip.
    Restore the backup to your new computer using the same tool used to back it up.
    Deauthorize the old computer if you no longer want to access protected content on it.
    Keep your backup up-to-date in future.
    Method 2
    Connect the two computers to the same network. Share your <User's Music> folder from the old computer and copy the entire iTunes library folder into the <User's Music> folder on the new one. Again, deauthorize the old computer if no longer required.
    Both methods should give the new computer a working clone of the library that was on the old one. As far as iTunes is concerned this is still the "home" library for your devices so you shouldn't have any issues with iTunes wanting to erase are reload.
    I'd recommend method 1 since it establishes an ongoing backup for your library.
    Should you be in the unfortunate position where you are no longer able to access your library or a backup of it then see Recover your iTunes library from your iPod or iOS device.
    tt2

  • When typing in a website after opening in a tab, the cursor focuses to the address bar and makes logging to things difficult, how do I change this?

    As stated in the question on any website I open regardless of whether it is a new tab or just a new destination, the cursor focuses on the address bar and makes logging in to sites very infuriating. Any help is much appreciated.

    Thanks for the help, it didn't help with this particular problem. I figured it out though, I had an issue with the AVG safe search. I had to just delete the file in the program files x86.

  • JList and ListModel, can anyone explain the basics?

    Hi
    I have an object A containing a Vector X of objects. I want to display them in a JList. I could always use DefaultListModel and copy the items of the Vector X into the default list model using addElement. But that would create a copy of the information in vector X. That is exactly why one should use a custom list model to ensure that the data is in sync with the GUI .
    I want to add and remove items from the JList, and simultaious add and remove items from the Vector X. Can anyone proviede a samll example of how to do this.
    I have tryed myselfe, but I can not get the JList updated with the changes of the listmodel. I have read the documentation about ListDataListener, but I just don't get it. A small example would realy be appreciated!
    // Mattias

    Yse I have read the tutorial. But I don't understand it.
    Here is a small example program. Can anyone change the code so the list is updated with the canges that obviously take place (as one can see by pressing the "Dump button")
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    class ListTest extends JFrame implements ActionListener , ListDataListener {
        JList list;
        MyListModel myListModel;
        MyDataObject myDataObject;
        ListTest() {
            JPanel p = new JPanel();
            myDataObject = new MyDataObject();
            myListModel = new MyListModel(myDataObject.x);
            list = new JList(myListModel);
            myListModel.addListDataListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            listScrollPane.setPreferredSize(new Dimension(200, 100));
            p.add(listScrollPane);
            JButton b1 = new JButton("Add");
            b1.addActionListener(this);
            p.add(b1);
            JButton b2 = new JButton("Remove");
            b2.addActionListener(this);
            p.add(b2);
            JButton b3 = new JButton("Dump");
            b3.addActionListener(this);
            p.add(b3);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(p);
            pack();
            show();
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Add")) {
                myListModel.addElement(""+ (1+myListModel.getSize()) );
                System.out.println("Added a row to the list");
            if (e.getActionCommand().equals("Remove")) {
                if (myListModel.getSize()>0) {
                    myListModel.remove(myListModel.getSize()-1);
                    System.out.println("Removed last element from the list");
                else {
                    System.out.println("No more elements to remove");
            if (e.getActionCommand().equals("Dump")) {
                System.out.println("\n\nData in the list model:");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myListModel.getElementAt(i));
                System.out.println("That should be the same as the vector x in the object myDataObject  :");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myDataObject.x.get(i));
        public void contentsChanged(ListDataEvent e) {
            System.out.println("contentsChanged");
        public void intervalAdded(ListDataEvent e) {
            System.out.println("intervalAdded");
        public void intervalRemoved(ListDataEvent e) {
            System.out.println("intervalRemoved");
        public static void main(String args[]) {
            new ListTest();
    class MyDataObject {
        Vector x;
        MyDataObject() {
            x=new Vector();
            x.addElement("1");
            x.addElement("2");
    class MyListModel extends AbstractListModel {
        Vector v;
        MyListModel(Vector v) {
            this.v=v;
        public void addElement(Object o) {
            v.addElement(o);
        public Object remove(int index) {
            return v.remove(index);
        public Object getElementAt(int index) {
            return v.get(index);
        public int getSize() {
            return v.size();
    </pre>

  • 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

  • Maintain Scroll Position And Focus On Postback for Grids and Child Grids

    I want to implement something like the asp MaintainScrollPositionOnPostback=True but for refreshing screens to the same position after refresh and maintain the focus on the grids/list and child grids/lists selected entries. Is there a way to do this?
    also I am forwarding from the order screen to the review orders screen using "Below Code" and would like to be able to focus on the person the order is for as the selection in the gid/list of the review screen shown
    partial void MedicationOrder_Saved()
    // Write your code here.
    this.Close(false);
    Application.ShowTimesAndMARs();
    //original code
    //Application.Current.ShowDefaultScreen(this.MedicationOrderDetailProperty);

    I want to implement something like the asp MaintainScrollPositionOnPostback=True but for refreshing screens to the same position after refresh and maintain the focus on the grids/list and child grids/lists selected entries. Is there a way to do this?
    I have no idea for this requirement, but I think you could consider implementing the highlighting of GridView row on row click and retain the selected row on postback.

  • Interesting Document: M2M, Internet of Things and Industry 4.0 – An Industry Perspective

    Hi All,
    here's an interesting document:
              M2M, Internet of Things and Industry 4.0 – An Industry Perspective
    Best regards,
    Andy.

    Hi All,
    here's an interesting document:
              M2M, Internet of Things and Industry 4.0 – An Industry Perspective
    Best regards,
    Andy.

  • Interesting occurance with 1gb ipod nano and on-the-go playlist creation ..

    interesting occurance with 1gb ipod nano and on-the-go playlist creation might be helpful to some.
    NOTE: the feedback form isnt up to date for software versions for 1gb ipod nano (newest here is 1.1.1 but i have 1.3.1).
    it seems i cannot create on-the-go playlist by holding album OR artist, with my 1gb ipod nano with VERSION 1.3.1 software, if there are various sizes of playlists in my ipod. i had about 4 playlists with 1 song in them and 2 -3 playlists with 5 - 30 songs in them. total space on ipod used was about 400mb of 896mb and about 1500 songs (most poor quality to save space (18-48kbs - i noticed some of the lower qualities have overtones of whistle or cricket like sounds (i have many ambient songs birds, thunder storms, etc)).
    i just manually deleted ALL playlists also deleted 945 songs on my ipod with itunes, and now i am able to do it. i can even do it now with composer or genre etc (which isnt listed in the playlist creation instructions). i now have 612 songs with 113mb free.
    p.s. i tried to leave this as bug feedback but got a strange message that was like a command pointing to a thank you for leaving feedback page.

    I have got this problem with my new 8gb nano too. Its very sad I had my mini stolen from my person whilst in a hospital bed dozing and it worked from the same itunes list and I could add albums or artists or songs now on the new replacment nano I can only add songs. Very annoying, please let me know if anyone can solve this. I too have reset and restored it numerous times. I am in the uk I think you are in the states.
    Windows xp   Windows XP  

  • Problems JList and DefaultListModel

    Hi!
    I've got a problem with the removing of items from a DefaultListModel.
    Assume this:
    public class ImageList extends JList implements DropTargetListener {
    private DefaultListModel dlm = new DefaultListModel();
    public void setListData(ArrayList al) {
    for(...) {
    //do some stuff here
    dlm.addElement(al.get(i));
    this.setModel(dlm);
    }In the main Frameclass are an instance of ImageList and a JButton for deleting a selected item from the list.
    content of the actionPerfomed-method of JButton:
    DefaultListModel model = (DefaultListModel)customContentPane.imageList.getModel();
    int index = customContentPane.imageList.getSelectedIndex();
    if(index!=-1) {
    imageData.remove(index);
    model.remove(index);
    }I'm developing with JBuilder and JDK 1.3.0_02 and there the removing works fine!
    But with JDK 1.4.1-rc-b19 i'm getting an ArrayIndexOutOfBoundsException when i try to delete the last item. The exceptions says index: 0, size: 0!
    But same code works without any problem with 1.3!!
    Does anybody knows a solution?
    Thanks in advance
    Martin

    Its me again!
    After some debugging i found out, the IndexOutOfBoundsException always gives 'Index: -1' back, although an item IS selected!
    And the imageList.getSelectedIndex() returns the true current selected item and not -1.
    Is it a bug in the JList and the DefaultListModel?

  • In Word and others, when I tip, regularly the focus quits the present window and i can't no more tip verry perturgbating

    In Word and other programs -  even in Safari - when I tip, the focus is suddently somewhere else and I tip nothing more.
    Extremely annoying: I have to tip twice the same things!
    the pointer of the mouse is also erratic

    Sorry, i wanted to write ' type ': when i type In word suddenly the pointer is somewhere else and i have to click in the windows to get the focus. Very annoying and Time consuming. I become crazy with this.
    best regards

  • Consume MouseEvent to prevent JList and JTree from receiving?!

    I have a JTree and a JList where I have made the CellRenderer so that it has a "button" area. When this button is clicked, I want something to happen. This I have achieved just nicely with a MouseListener, as per suggestion from JavaDocs.
    However, the problem is that when a click is deemed to be within the "button", I do not want the tree or list to process it anymore. But doing e.consume(), both on mousePressed or mouseClicked (though it obviously is pressed the JList and JTree themselves listen to) doesn't do jack.
    How can I achieve this functionality?

    da.futt wrote:
    stolsvik wrote:
    Okay, I managed with a hack: It is the order of listeners that's the problem: The ListUI's MouseListener is installed before mine, and hence will get the MouseEvent before me, so it has already processed it when I get it, and hence consuming it makes no difference. No. Normally, listeners are notified latest-registered to earliest-registered. I don't remember seeing an exception to that rule in the core API. well, you are both right (or wrong ;-) - the rule is: the order of listener notification is undefined, it's an implementation detail which listeners must not rely on. "Anecdotical" experience is that AWTListeners are notified first-registered-first-served, while listeners to swing specific events are notified last-registered-first-served. Below is a snippet (formulated in context of SwingX convenience classes, too lazy ...) showing that difference.
    The latter probably stems from hefty c&p of notification by walking the EventListenerList: the earliest code was implemented very near the beginning of Swing when every little drop of assumed performance optimization was squeezed, such as walking from back to front. Using EventListenerList involves lots of code duplication ... so lazy devs as we all are, simply c&p'ed that loop and just changed the concrete event type and method name. More recently, as in the we-use-all-those-nifty-cool-language-features ;-) I've seen more usage of forEach loops (f.i. in beansbinding) so notification is back to first-in-first-served :-)
    Bottom line: don't rely on any sequence - if needed, use an eventBus (or proxy or however it's called) and define the order there. Darryl's suggestion is as close as we can get in Swing (as it's not supported) but not entirely safe: there's no way to get notified when listeners are added/removed and no hook where to plug-in such a bus into the ui-delegate where it would belong.
    Cheers
    Jeanette
    // output
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$1 mousePressed
    INFO: first added mouseListener
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$2 mousePressed
    INFO: second added mouseListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$4 valueChanged
    INFO: second added listSelectionListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$3 valueChanged
    INFO: first added listSelectionListener
    // produced by
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.logging.Logger;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.test.AncientSwingTeam;
    public class EventOrderCheck extends InteractiveTestCase {
        public void interactiveOrderAWTEvent() {
            JList list = new JList(AncientSwingTeam.createNamedColorListModel());
            MouseListener first = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("first added mouseListener");
            MouseListener second = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("second added mouseListener");
            list.addMouseListener(first);
            list.addMouseListener(second);
            ListSelectionListener firstSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("first added listSelectionListener");
            ListSelectionListener secondSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("second added listSelectionListener");
            list.addListSelectionListener(firstSelection);
            list.addListSelectionListener(secondSelection);
            showWithScrollingInFrame(list, "event order");
        @SuppressWarnings("unused")
        private static final Logger LOG = Logger.getLogger(EventOrderCheck.class
                .getName());
        public static void main(String[] args) {
            EventOrderCheck test = new EventOrderCheck();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

Maybe you are looking for