Popup on JList????

Hi,
I'm trying to add a right-click popup function
to a JList. Could someone help me?
Here is what I've done:
          JList clientList = new JList(new DefaultListModel());
          model = (DefaultListModel)clientList.getModel();
          clientList.setVisibleRowCount( 11 );
          clientList.setFixedCellWidth( 100 );
          clientList.setFixedCellHeight( 15 );
          clientList.setSelectionMode(
               ListSelectionModel.SINGLE_INTERVAL_SELECTION );
               // define a MouseListener for the window that displays
                  // a JPopupMenu when the popup trigger event occurs
               clientList.addMouseListener(
                   // anonymous inner class to handle mouse events
                   new MouseAdapter() {
                      // handle mouse press event
                      public void mousePressed( MouseEvent event )
                         checkForTriggerEvent( event );
                      // handle mouse release event
                      public void mouseReleased( MouseEvent event )
                         checkForTriggerEvent( event );
                      // determine whether event should trigger popup menu
                      private void checkForTriggerEvent( MouseEvent event )
                         if ( event.isPopupTrigger() )
                            popupMenu.show( event.getComponent(),
                               event.getX(), event.getY() );
                ); // end call to addMouseListenerWhen the user right-clicks on the JList, I want the popup to depend on
which item within the list had been right-clicked.
I don't know where to put the functionality to determine which item was clicked.
If you can help, could you please explain it using some sample code!
Thanks

The easiest way I know of to make a JList object responsive to right mouse clicks is first to get the Point of the click, then pass that Point to the locationToIndex method in the JList class. That method returns the index of the JList item that was under the mouse click. Once you have the index, you can then programmatically select the item in the JList with the setSelectedIndex method. Sample code follows:
     private class MouseTracker extends MouseAdapter
          public void mouseReleased(MouseEvent me)
               if (me.isPopupTrigger())
                    Point p = me.getPoint();
                    int index = list.locationToIndex(p);
                    list.setSelectedIndex(index);
                    popupMenu.show(me.getComponent(),p.x,p.y);
               }//end if
          }//end mouseReleased
     };//end inner class

Similar Messages

  • Removing PopUp from JList

    Hi!
    I have a small problem with popup menus in a JList. When I right click on an entry in the JList, the menu is shown. However, there is possible to change the selected entry in the list with the arrowkeys and the popup menu does not dissapear then. How can I do so that the popup is hidden when I change selected value?
    Thanks in advance,
    // Andreas

    EditLurk.java [70:1] Class Javax.swing.JList not found in type declaration or import.
    adminList = new Javax.swing.JList(adminModel);
    ^
    EditLurk.java [70:1] No constructor in JList matches <init>(DefaultListModel)
    adminList = new Javax.swing.JList(adminModel);
    ^

  • Popup menus over elements in a JList

    Hi,
    How would I create a Popup menu when I select an element in a single selection only JList?
    Is it possible to have the popup show on any selection event (keyboard, mouse, or even by programatically causing an element to be selected)?
    thanks.

    I kind of got the behavior I want with doing following, but when I try to use this approach in an Applet, I get an ugly Java Applet Window message:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTest extends JFrame implements ActionListener{
    DefaultListModel lm = new DefaultListModel();
    JList list = new JList(lm);
    JScrollPane scroll = new JScrollPane(list);
    JPanel p = new JPanel(new BorderLayout());
    JPopupMenu popup = new JPopupMenu();
    JMenuItem menuItem;
    public MenuTest(){
         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         lm.addElement("one");
         lm.addElement("two");
         lm.addElement("three");
         lm.addElement("four");
         getContentPane().add(p, BorderLayout.CENTER);
         p.add(scroll, BorderLayout.CENTER);
         menuItem = new JMenuItem("print to stdout");
         menuItem.addActionListener(this);
         popup.add(menuItem);
         list.addMouseListener(new MouseAdapter(){
              public void mouseReleased(MouseEvent e){
              int index = list.locationToIndex(e.getPoint());
              if (index>-1&&!(list.isSelectionEmpty())){
                   popup.show(e.getComponent(), e.getX(), e.getY());
         addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void actionPerformed(ActionEvent e){
         System.out.println((String) list.getSelectedValue());
    public static void main(String args[]){
         MenuTest window = new MenuTest();
         window.setTitle("MenuTest");
         window.setSize(200, 300);
         window.setVisible(true);
    It seems the behavior is different than for frames and in my GNOME desktop manager when I run my applet it opens a new window for the PopupMenu.
    If anyone has run into this and has a work around please let me know.
    thanks

  • Separator is not showing up in the JList that is set in the TextField

    Hi,
    This problem is really weird and I am tired trying to find the problem and so thought i ll ask u guys... i cant see any problem in the code below.. but when i run it the separator that i want if some condition is true it just dsnt come... i did debug it and it does actually go in the if condition but the separator is not showing up... i dont kno y...
    I am pasting the code of the JList renderer SearchListCellRenderer that implements ListCellRenderer.......it has only one method....
    public Component getListCellRendererComponent(JList list, Object value,
                   int     index, boolean isSelected, boolean cellHasFocus) {
              JLabel label = null;
              if (value != null){
                   label = new JLabel();/*(JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
                   isSelected, cellHasFocus);*/
                   if(!anatomySeparator && anatomyMap.containsKey(value.toString().toLowerCase())){
                        label.setVerticalTextPosition(SwingConstants.BOTTOM);
                        label.setPreferredSize(new Dimension(300, 80));
                        label.setText("<html><body>" + "<p style='color:white;'><b>--------------Anatomy--------------</b></p>" + "<p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
                        anatomySeparator = true;
                        logger.debug("in anatomy");
                   }else if(!diseaseSeparator && diseaseMap.containsKey(value.toString().toLowerCase())){
                        label.setVerticalTextPosition(SwingConstants.BOTTOM);
                        label.setPreferredSize(new Dimension(300, 80));
                        label.setText("<html><body>" + "<p style='color:white;'><b>---------------Diseases----------------</b></p>" + "<p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
                        diseaseSeparator = true;
                        logger.debug("in disease");
                   }else if(!propSeparator && observationMap.containsKey(value.toString().toLowerCase())){
                        label.setVerticalTextPosition(SwingConstants.BOTTOM);
                        label.setPreferredSize(new Dimension(300, 80));
                        label.setText("<html><body>" + "<p style='color:white;'><b>-----------Observations----------------</b></p>" + "<p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
                        propSeparator = true;
                        logger.debug("in observation");
                   }else{
                        label.setPreferredSize(new Dimension(300, 30));
                        label.setText("<html><body><p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
              return label;
    If i see the output the list in the JList is bold also in the condition i have the label size larger so in some values the label is actually large than others... that means it does go in the if condition... but the separator that i have there it just dsnt show up... i dnt kno wat is wrong... can anyone pls help me with this????
    This is how i set the autocopleter text field with the Jlist and its renderer... if that is of some help.....
    JList list = new JList();
    JPopupMenu popup = new JPopupMenu();
    JTextComponent textComp;
    private static final String AUTOCOMPLETER = "AUTOCOMPLETER"; //NOI18N
    public SearchListCellRenderer renderer;
    public AutoCompleter(JTextComponent comp){
    textComp = comp;
    textComp.putClientProperty(AUTOCOMPLETER, this);
    JScrollPane scroll = new JScrollPane(list);
    scroll.setBorder(null);
    list.setFocusable( false );
    list.setBackground(Color.DARK_GRAY);
    list.setForeground(Color.WHITE);
    renderer = new SearchListCellRenderer();
    list.setCellRenderer(renderer);
    scroll.getVerticalScrollBar().setFocusable( false );
    scroll.getHorizontalScrollBar().setFocusable( false );
    popup.setBorder(BorderFactory.createLineBorder(Color.black));
    popup.add(scroll);
    if(textComp instanceof JTextField){
    textComp.registerKeyboardAction(showAction, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_FOCUSED);
    textComp.getDocument().addDocumentListener(documentListener);
    }else
    textComp.registerKeyboardAction(showAction, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_MASK), JComponent.WHEN_FOCUSED);
    textComp.registerKeyboardAction(upAction, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_FOCUSED);
    textComp.registerKeyboardAction(hidePopupAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_FOCUSED);
    popup.addPopupMenuListener(new PopupMenuListener(){
    public void popupMenuWillBecomeVisible(PopupMenuEvent e){
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e){
    textComp.unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
    public void popupMenuCanceled(PopupMenuEvent e){
    list.setRequestFocusEnabled(false);
    }

    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • What is the Popup class used for

    I always thought that a Popup should have some basic functionality, such as the pupup should close when:
    a) the escape key is pressed
    b) the popup loses focus
    The popup class provides none of the above functionality and in     fact seems to require some obscure code to
    even get the keyboard focus to work properly.
    Using a JWindow seems to provide the same functionality as a Popup.
    JPopupMenu seems to support both of the above requirements.
    Run the following program:
    a) click on each of the buttons
    b) click on an empty part of the frame
    It appears to me that whenever you need a "popup" you should use a JPopupMenu.
    Is the Popup class good for anything? Does it provide any functionality that I am not aware of?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class PopupTest extends JFrame
         String[] numbers = { "one", "two", "three", "four", "five" };
         public PopupTest()
              getContentPane().setLayout( new FlowLayout() );
              JButton popup = new JButton("Popup as Popup");
              popup.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        popupPopup(e);
              getContentPane().add(popup);
              JButton window = new JButton("Window as Popup");
              window.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        windowPopup(e);
              getContentPane().add(window);
              JButton menu = new JButton("PopupMenu as Popup");
              menu.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        menuPopup(e);
              getContentPane().add(menu);
         private void popupPopup(ActionEvent e)
              JList list = new JList(numbers);
              list.setSelectedIndex(0);
              PopupFactory factory = PopupFactory.getSharedInstance();
              Popup popup = factory.getPopup(this, list, getLocation().x, getLocation().y);
              popup.show();
              Window window = SwingUtilities.windowForComponent(list);
              if (window != null)
                   window.setFocusableWindowState(true);
              KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(list);
         private void windowPopup(ActionEvent e)
              JList list = new JList(numbers);
              list.setSelectedIndex(0);
              JWindow window = new JWindow(this);
              window.getContentPane().add(list);
              window.pack();
              window.setVisible(true);
              window.setLocation(getLocation().x + 200, getLocation().y);
         private void menuPopup(ActionEvent e)
              JList list = new JList(numbers);
              list.setSelectedIndex(0);
              Component c = (Component)e.getSource();
              JPopupMenu menu = new JPopupMenu();
              menu.add(list);
              menu.show(c, 0, 0);
              list.requestFocusInWindow();
         public static void main(String[] args)
              PopupTest frame = new PopupTest();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setSize(500, 200);
              frame.setLocationRelativeTo( null );
              frame.show();
    }

    you'd use Popup like JPopupMenu does, via a PopupFactoryYes you can get the Popu from the PopupFactory, but I think you are missing the point of my question. Popup has two methods, hide/show. It provides no other funtionality. I must write code to handle the escapce key and close the popup when it loses focus.
    When I use a JPopupMenu and add a component to the menu, it appears to add some listeners to the component to handle the escape key and loss of focus.
    I think it's safe to say that you're right when you say that it's preferable to use
    JPopupMenu (my experience as well).That was my conclusion, but I was just wondering it I was missing anything.
    It turns out that there are used in tooltips which, by essence, don't need any
    input from the user (whether keyboard or mouse) I guess thats what I was missing, only use a Popup in tooltip type situations.

  • Combo box popup width adjusting no longer work in 1.0.6_26-b03

    Previously, I was able to adjusting combo box popup's width, by referring to the technique described in [http://tips4java.wordpress.com/2010/11/28/combo-box-popup/|http://tips4java.wordpress.com/2010/11/28/combo-box-popup/]. During that time, I was using 1.0.6_24-b07.
    However, after I update my Java runtime to 1.0.6_26-b03, things broke.
    Here is the screen shoot.
    [Workable screen shoot|http://i.imgur.com/0elo7.png]
    [Not workable screen shoot|http://i.imgur.com/BeKMy.png]
    Here is the code snippet to demonstrate this problem.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * NewJFrame.java
    * Created on Aug 9, 2011, 4:13:41 AM
    package experiment;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    import javax.swing.plaf.basic.BasicComboPopup;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
         * Adjust popup for combo box, so that horizontal scrollbar will not display.
         * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
         * http://www.camick.com/java/source/BoundsPopupMenuListener.java
         * @param comboBox The combo box
        public static void adjustPopupWidth(JComboBox comboBox) {
            if (comboBox.getItemCount() == 0) return;
            Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
            if (!(comp instanceof BasicComboPopup)) {
                return;
            BasicComboPopup popup = (BasicComboPopup)comp;
            JList list = popup.getList();
            JScrollPane scrollPane = getScrollPane(popup);
            // Just to be paranoid enough.
            if (list == null || scrollPane == null) {
                return;
            //  Determine the maximimum width to use:
            //  a) determine the popup preferred width
            //  b) ensure width is not less than the scroll pane width
            int popupWidth = list.getPreferredSize().width
                            + 5  // make sure horizontal scrollbar doesn't appear
                            + getScrollBarWidth(popup, scrollPane);
            Dimension scrollPaneSize = scrollPane.getPreferredSize();
            popupWidth = Math.max(popupWidth, scrollPaneSize.width);
            //  Adjust the width
            scrollPaneSize.width = popupWidth;
            scrollPane.setPreferredSize(scrollPaneSize);
            scrollPane.setMaximumSize(scrollPaneSize);
         *  I can't find any property on the scrollBar to determine if it will be
         *  displayed or not so use brute force to determine this.
        private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
            int scrollBarWidth = 0;
            Component component = popup.getInvoker();
            if (component instanceof JComboBox) {
                JComboBox comboBox = (JComboBox)component;
                if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
                    JScrollBar vertical = scrollPane.getVerticalScrollBar();
                    scrollBarWidth = vertical.getPreferredSize().width;
            return scrollBarWidth;
         *  Get the scroll pane used by the popup so its bounds can be adjusted
        private static JScrollPane getScrollPane(BasicComboPopup popup) {
            JList list = popup.getList();
            Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
            return (JScrollPane)c;
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jComboBox1.addPopupMenuListener(getPopupMenuListener());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "This is a very long text. This is a very long text" }));
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(82, 82, 82)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(242, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(246, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        private PopupMenuListener getPopupMenuListener() {
            return new PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    // We will have a much wider drop down list.
                    adjustPopupWidth(jComboBox1);
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }

    I had came across another workaround as stated here.
    [http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough|http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough]
    The popup's is having enough width to show all items. However, it is not perfect still, as the width is little too much. I still can see some extra space at the tailing of the list.
    The workaround is as follow.
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    // got this workaround from the following bug:
    //      http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4618607
    public class WideComboBox extends JComboBox{
        public WideComboBox() {
        public WideComboBox(final Object items[]){
            super(items);
        public WideComboBox(Vector items) {
            super(items);
        public WideComboBox(ComboBoxModel aModel) {
            super(aModel);
        private boolean layingOut = false;
        public void doLayout(){
            try{
                layingOut = true;
                super.doLayout();
            }finally{
                layingOut = false;
        public Dimension getSize(){
            Dimension dim = super.getSize();
            if(!layingOut)
                dim.width = Math.max(dim.width, getPreferredSize().width);
            return dim;
    }

  • Scroll bar in JPopupMenu when used in JList

    Hi,
    I want variable list (not combo box) where I can add multiple JMenuItems through JPopupMenu. I have created JList in JScrollPane and I have added multiple JMenuItems one by one but in output I am getting the list of JMenuItems without scrollbar. There is no way I can navigate to last JMenuItem in the JList. Could someone help me with integration of JList, JMenuItems, JPopupMenu with scroll bars?
    Below given is the sample code. GUI components have been added through Netbeans.
    public void updatePopUp()
    final JPopupMenu menu = new JPopupMenu();
    menu.setBorder(null);
    menu.setAutoscrolls(true);
    JMenuItem item = new JMenuItem("JMenuItem");
    item.addActionListener(this);
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    menu.setVisible(true);
    menu.pack();
    varList.add(menu);
    // Set the component to show the popup menu
    /* this.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    public void mouseReleased(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    }

    I was going to say try setting the preferred (or maximum) size of the scrollpane to force it to be no larger than you want.
    But ...
    a) I don't see you putting menu items in a JList in that code. You are putting them directly into the popup menu (aka, the normal way to do things).
    b) Calling setAutoscrolls() on the JPopupMenu does not make it a "scrollable" menu. It is for supporting dragging of components in a scrollpane (usually). Read the API docs.

  • 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

  • Popups, focus, and J2SDK 1.4.2

    Hi,
    I have a program that draws a cartoon of a physical device in a JPanel and monitors mouse position, movement and left-clicks on the cartoon. When the user clicks a particular region of the cartoon, a popup containing a JTextField is displayed and given the focus, allowing the user to change the label for that part of the cartoon.
    All this works fine with every 1.4.1 SDK that I've tried. However, if I run the program under any 1.4.2 release, odd things happen. At first, things appear to work normally, but if the program displays a modal dialog like a JFileChooser or a JOptionPane, then dismisses the dialog, a JTextField in the popup that is brought up where the dialog appeared can no longer be given the focus. The problem appears to be associated with the region of the screen where the dialog appeared, not the window position since you can move the program window to a different location and the program will appear to work normally. Move it back to its original position and the "dead" area where the dialog was displayed still won't accept focus.
    I've simplified the original program substantially and can reproduce it with the program listed below.
    * FocusProblem.java
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.*;
    * Illustrate problem with obtaining focus after overlaying panel with
    * a dialog.
    public final class FocusProblem extends JFrame {
        private boolean editing;    // is the editor displayed or not
        private int xPos;           // mouse positions from mouse events
        private int yPos;
        private final JTextField chpEd;
        private final JPanel buttonPanel;
        private final JPanel clickPanel;
        private final JButton theButton;
        private Popup popup;
        private final PopupFactory factory = PopupFactory.getSharedInstance();
        public FocusProblem() {
            editing = false;
            xPos = yPos = -1;
            addWindowListener(new WindowAdapter() {
                public void windowClosing(final WindowEvent evt) {
                    exitForm(evt);
            clickPanel = new JPanel();
            clickPanel.setPreferredSize(new Dimension(600, 400));
            getContentPane().add(clickPanel, BorderLayout.CENTER);
            theButton = new JButton("Show Dialog");
            theButton.addActionListener(new ActionListener() {
                public void actionPerformed(final ActionEvent evt) {
                    theButtonActionPerformed(evt);
            buttonPanel = new JPanel();
            buttonPanel.setBorder(new EtchedBorder());
            buttonPanel.add(theButton);
            getContentPane().add(buttonPanel, BorderLayout.EAST);
            pack();
            chpEd = new JTextField(10);
            // set up the mouse listeners
            final MyListener myListener = new MyListener();
            clickPanel.addMouseListener(myListener);
            clickPanel.addMouseMotionListener(myListener);
         * Handle a click on the button.
         * @param evt Not used.
        private void theButtonActionPerformed(final ActionEvent evt) {
            JOptionPane.showMessageDialog(this, "Just for testing", "A Modal Dialog",
                    JOptionPane.INFORMATION_MESSAGE);
         * Handle a click on the close decoration.
         * @param evt Not used.
        private static void exitForm(final WindowEvent evt) {
            System.exit(0);
        // Editor related methods.
         * Bring up the <code>JTextField</code> over the panel where clicked.
         * Highlight the contents of the test field.
        private void bringUpEditor() {
            editing = true;
            clickPanel.setToolTipText(null);
            chpEd.setText("X = " + xPos + ", Y = " + yPos);
            final Point p = new Point(xPos, yPos);
            // getPopup expects screen coordinates, so do the conversion
            SwingUtilities.convertPointToScreen(p, this);
            popup = factory.getPopup(clickPanel, chpEd, p.x, p.y);
            popup.show();
            chpEd.setVisible(true);
            if (chpEd.requestFocusInWindow() != true) {
                System.out.println("Failed to obtain focus");
    //        chpEd.requestFocus();
    //        chpEd.grabFocus();
            chpEd.getCaret().setDot(0);
            chpEd.getCaret().moveDot(chpEd.getText().length());
         * Hide the editor and set <code>editing</code>
         * to <code>false</code>.
        private void takeDownEditor() {
            popup.hide();
            popup = null;
            editing = false;
        // MouseInputAdapter methods
        final class MyListener extends MouseInputAdapter {
             * Watch mouse clicks on the panel. If the global variable
             * <code>editing</code> is <code>true</code>, the click occurred
             * outside of the editor, so any changes in the editor are
             * accepted and the editor is take down. If <code>editing</code>
             * is <code>false</code>, start editing at the position of the click.
             * @param e The <code>MouseEvent</code> to be responded to. Used
             * to retrieve the mouse position.
            public void mousePressed(final MouseEvent e) {
                if (editing) {
                    takeDownEditor();
                } else {
                    xPos = e.getX();
                    yPos = e.getY();
                    bringUpEditor();
             * Watch for mouse moves. If the global variable <code>editing</code>
             * is <code>false</code>, set the text of the panel's tooltip to the
             * mouse location.
             * @param e The <code>MouseEvent</code> to be responded to. Used to
             * retrieve the mouse position.
            public void mouseMoved(final MouseEvent e) {
                if (!editing) {
                    xPos = e.getX();
                    yPos = e.getY();
                    clickPanel.setToolTipText("X = " + xPos + ", Y = " + yPos);
         * A program entry point to run the test.
         * @param args Not used.
        public static void main(final String[] args) {
            new FocusProblem().show();
    }To observe the problem:
    1. Start the program and allow the mouse to hover near the center of the left panel. A tooltip should appear with the position of the mouse.
    2. Click and a popup with an editor should be brought up. The JTextField should have the focus. Click somewhere else to dismiss the editor.
    3. Click the button in the right pane to display a dialog. over a region of the left panel. Dismiss the dialog.
    4. Click in the area where the dialog was displayed. If running 1.4.1, the JTextField will be focused, just as in step 2. If running 1.4.2, the popup will appear with the JTextField but will not have foucs and will not accept focus by clicking (or any other method I've been able to find.)
    I've observed this problem with Linux (Redhat 9), Windows 98, Win2K, and WinXP on PIII and P4's. The problem occurs with J2SDK 1.4.1 and 1.4.2_01.
    I posted this as a bug right after 1.4.2 came out, but have only received the usual automated reply from Sun. Can't find it in the bug database. Am I missing something or is this really a bug? Any workarounds?
    Other Weirdness
    I've also noticed that if you run the program and let the mouse hover long enough for the tooltip to appear, then move the mouse down so that the tooltip appears to "touch" the bottom border, the tooltip will begin to flicker a lot when you move the mouse around higher in the window when running 1.4.2. Doesn't happen with any J2SDK 1.4.1 release that I've tried. Is this another manifestation of the problem described above?
    Thanks in advance for all the help.

    I'm wondering if you've been able to reconcile the problem. I have exactly the same situation. I've tried everything I could think of, but whenever I call popup.show() followed by a call to requestFocusInWindow,
    I get a false return - meaning of course the popup (or more precisely a JList in the popup) can NOT receive the focus. Same behavior as yours. I really liked the way it worked under 1.4.1 and hate to give it up. Surely hope you've figured it out and can share with me.

  • Autocomplete popup list menu

    Hi,
    I am impressed by the autocomplete feature when I type in text editor of the netbeans. You know, when I type javax.swing. then I wait for seconds, or press Ctrl-Space, it will popup menu. The popup menu will offer me some word to complete the word "javax.swing.", maybe word like border, JTextField, JTable. So you just press arrow to choose the word. Very convenient. How do I make that kind of popup menu but this time I want to make in cell of the jtable. So if I type something in cell of the jtable, it will check the word I type and popup autocomplete list menu with scrollpane too according the word I type. If I type "wel" then it will offer word "come".
    Thank you.
    Regards,
    akbar

    Hello.
    I have something that might help you. Here is the story : I use IntelliJ IDEA at work and I like very much its auto-completion feature (much better than that of Visual Studio). I like it and use it so much that I often find myself hitting control+space in almost any type text editor.
    At one point, I said to myself : why not exporting the concept to a text editor and enable auto-completion for normal text (not just code). This is why I coded the following class (and later completely forgot about it until now).
    It requires a lexicon file containing the words subject to auto-completion. You can easily modify it and pass a String[].
    Hope it'll help you.import javax.swing.*;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.JTextComponent;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Set;
    import java.util.TreeSet;
    import java.util.Iterator;
    * <dl>
    * <dt><b>Creation date :</b></dt>
    * <dd> 8 oct. 2003 </dd>
    * </dl>
    * @author Pierre LE LANNIC
    public class PowerEditor extends JPanel {
         private Set theSet;
         private WordMenuWindow theWordMenu;
         private JTextComponent theTextComponent;
         private Window theOwner;
         private static final char[] WORD_SEPARATORS =
                   {' ', '\n', '\t', '.', ',', ';', '!', '?', '\'', '(', ')', '[', ']', '\"', '{', '}', '/', '\\', '<', '>'};
         private Word theCurrentWord;
         private class Word {
              private int theWordStart;
              private int theWordLength;
              public Word() {
                   theWordStart = -1;
                   theWordLength = 0;
              public void setBounds(int aStart, int aLength) {
                   theWordStart = Math.max(-1, aStart);
                   theWordLength = Math.max(0, aLength);
                   if (theWordStart == -1) theWordLength = 0;
                   if (theWordLength == 0) theWordStart = -1;
              public void increaseLength(int newCharLength) {
                   int max = theTextComponent.getText().length() - theWordStart;
                   theWordLength = Math.min(max, theWordLength + newCharLength);
                   if (theWordLength == 0) theWordStart = -1;
              public void decreaseLength(int removedCharLength) {
                   theWordLength = Math.max(0, theWordLength - removedCharLength);
                   if (theWordLength == 0) theWordStart = -1;
              public int getStart() {
                   return theWordStart;
              public int getLength() {
                   return theWordLength;
              public int getEnd() {
                   return theWordStart + theWordLength;
              public String toString() {
                   String toReturn = null;
                   try {
                        toReturn = theTextComponent.getText(theWordStart, theWordLength);
                   } catch (BadLocationException e) {
                   if (toReturn == null) toReturn = "";
                   return toReturn;
         private class WordMenuWindow extends JWindow {
              private JList theList;
              private DefaultListModel theModel;
              private Point theRelativePosition;
              private class WordMenuKeyListener extends KeyAdapter {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                             onSelected();
              private class WordMenuMouseListener extends MouseAdapter {
                   public void mouseClicked(MouseEvent e) {
                        if ((e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 2)) {
                             onSelected();
              public WordMenuWindow() {
                   super(theOwner);
                   theModel = new DefaultListModel();
                   theRelativePosition = new Point(0, 0);
                   loadUIElements();
                   setEventManagement();
              private void loadUIElements() {
                   theList = new JList(theModel) {
                        public int getVisibleRowCount() {
                             return Math.min(theModel.getSize(), 10);
                   theList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                   theList.setBackground(new Color(235, 244, 254));
                   JScrollPane scrollPane = new JScrollPane(theList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   scrollPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
                   setContentPane(scrollPane);
              private void setEventManagement() {
                   theList.addKeyListener(new WordMenuKeyListener());
                   theList.addMouseListener(new WordMenuMouseListener());
              private void onSelected() {
                   String word = (String)theList.getSelectedValue();
                   setCurrentTypedWord(word);
              public void display(Point aPoint) {
                   theRelativePosition = aPoint;
                   Point p = theTextComponent.getLocationOnScreen();
                   setLocation(new Point(p.x + aPoint.x, p.y + aPoint.y));
                   setVisible(true);
              public void move() {
                   if (theRelativePosition != null) {
                        Point p = theTextComponent.getLocationOnScreen();
                        setLocation(new Point(p.x + theRelativePosition.x, p.y + theRelativePosition.y));
              public void setWords(String[] someWords) {
                   theModel.clear();
                   if ((someWords == null) || (someWords.length == 0)) {
                        setVisible(false);
                        return;
                   for (int i = 0; i < someWords.length; i++) {
                        theModel.addElement(someWords);
                   pack();
                   pack();
              public void moveDown() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.min(theModel.getSize() - 1, current + 1);
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
              public void moveUp() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.max(0, current - 1);
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
              public void moveStart() {
                   if (theModel.getSize() < 1) return;
                   theList.setSelectionInterval(0, 0);
                   theList.scrollRectToVisible(theList.getCellBounds(0, 0));
              public void moveEnd() {
                   if (theModel.getSize() < 1) return;
                   int endIndex = theModel.getSize() - 1;
                   theList.setSelectionInterval(endIndex, endIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(endIndex, endIndex));
              public void movePageUp() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.max(0, current - Math.max(0, theList.getVisibleRowCount() - 1));
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
              public void movePageDown() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.min(theModel.getSize() - 1, current + Math.max(0, theList.getVisibleRowCount() - 1));
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
         public PowerEditor(Set aLexiconSet, JFrame anOwner, JTextComponent aTextComponent) {
              super(new BorderLayout());
              theOwner = anOwner;
              theTextComponent = aTextComponent;
              theWordMenu = new WordMenuWindow();
              theSet = aLexiconSet;
              theCurrentWord = new Word();
              loadUIElements();
              setEventManagement();
         public JTextComponent getTextComponent() {
              return theTextComponent;
         private void loadUIElements() {
              add(theTextComponent, BorderLayout.CENTER);
         private void setEventManagement() {
              theTextComponent.addFocusListener(new FocusAdapter() {
                   public void focusLost(FocusEvent e) {
                        theTextComponent.requestFocus();
              theTextComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_MASK), "controlEspace");
              theTextComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK), "home");
              theTextComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), "end");
              theTextComponent.getActionMap().put("controlEspace", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        onControlSpace();
              theTextComponent.getActionMap().put("home", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        theWordMenu.moveStart();
              theTextComponent.getActionMap().put("end", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        theWordMenu.moveEnd();
              theTextComponent.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent e) {
                        super.mouseClicked(e);
                        if (theWordMenu.isVisible()) {
                             theWordMenu.setVisible(false);
              theTextComponent.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.isConsumed()) return;
                        if (theWordMenu.isVisible()) {
                             if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                                  theWordMenu.onSelected();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                                  theWordMenu.moveDown();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_UP) {
                                  theWordMenu.moveUp();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) {
                                  theWordMenu.movePageDown();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_PAGE_UP) {
                                  theWordMenu.movePageUp();
                                  e.consume();
              theOwner.addComponentListener(new ComponentAdapter() {
                   public void componentHidden(ComponentEvent e) {
                        theWordMenu.setVisible(false);
                   public void componentMoved(ComponentEvent e) {
                        if (theWordMenu.isVisible()) {
                             theWordMenu.move();
              theTextComponent.getDocument().addDocumentListener(new DocumentListener() {
                   public void insertUpdate(DocumentEvent e) {
                        if (theWordMenu.isVisible()) {
                             int beginIndex = e.getOffset();
                             int endIndex = beginIndex + e.getLength();
                             String newCharacters = theTextComponent.getText().substring(beginIndex, endIndex);
                             for (int i = 0; i < WORD_SEPARATORS.length; i++) {
                                  if (newCharacters.indexOf(WORD_SEPARATORS[i]) != -1) {
                                       theCurrentWord.setBounds(-1, 0);
                                       theWordMenu.setWords(null);
                                       theWordMenu.setVisible(false);
                                       return;
                             theCurrentWord.increaseLength(e.getLength());
                             updateMenu();
                   public void removeUpdate(DocumentEvent e) {
                        if (theWordMenu.isVisible()) {
                             theCurrentWord.decreaseLength(e.getLength());
                             if (theCurrentWord.getLength() == 0) {
                                  theWordMenu.setWords(null);
                                  theWordMenu.setVisible(false);
                                  return;
                             updateMenu();
                   public void changedUpdate(DocumentEvent e) {
         private String[] getWords(String aWord) {
              aWord = aWord.trim().toLowerCase();
              Set returnSet = new TreeSet();
              for (Iterator iterator = theSet.iterator(); iterator.hasNext();) {
                   String string = (String)iterator.next();
                   if (string.startsWith(aWord)) {
                        returnSet.add(string);
              return (String[])returnSet.toArray(new String[0]);
         private static boolean isWordSeparator(char aChar) {
              for (int i = 0; i < WORD_SEPARATORS.length; i++) {
                   if (aChar == WORD_SEPARATORS[i]) return true;
              return false;
         private void onControlSpace() {
              theCurrentWord = getCurrentTypedWord();
              if (theCurrentWord.getLength() == 0) return;
              int index = theCurrentWord.getStart();
              Rectangle rect = null;
              try {
                   rect = theTextComponent.getUI().modelToView(theTextComponent, index);
              } catch (BadLocationException e) {
              if (rect == null) return;
              theWordMenu.display(new Point(rect.x, rect.y + rect.height));
              updateMenu();
              theTextComponent.requestFocus();
         private void updateMenu() {
              if (theCurrentWord.getLength() == 0) return;
              String[] words = getWords(theCurrentWord.toString());
              theWordMenu.setWords(words);
         private Word getCurrentTypedWord() {
              Word word = new Word();
              int position = theTextComponent.getCaretPosition();
              if (position == 0) return word;
              int index = position - 1;
              boolean found = false;
              while ((index > 0) && (!found)) {
                   char current = theTextComponent.getText().charAt(index);
                   if (isWordSeparator(current)) {
                        found = true;
                        index++;
                   } else {
                        index--;
              word.setBounds(index, position - index);
              return word;
         private void setCurrentTypedWord(String aWord) {
              theWordMenu.setVisible(false);
              if (aWord != null) {
                   if (aWord.length() > theCurrentWord.getLength()) {
                        String newLetters = aWord.substring(theCurrentWord.getLength());
                        try {
                             theTextComponent.getDocument().insertString(theCurrentWord.getEnd(), newLetters, null);
                        } catch (BadLocationException e) {
                        theCurrentWord.increaseLength(newLetters.length());
              theTextComponent.requestFocus();
              theTextComponent.setCaretPosition(theCurrentWord.getEnd());
              theCurrentWord.setBounds(-1, 0);
         private static Set loadLexiconFromFile(File aFile) throws IOException {
              Set returnSet = new TreeSet();
              BufferedReader reader = new BufferedReader(new FileReader(aFile));
              String line = reader.readLine();
              while (line != null) {
                   returnSet.add(line);
                   line = reader.readLine();
              reader.close();
              return returnSet;
         public static void main(String[] args) {
              try {
                   File lexiconFile = new File("./lexicon.txt");
                   Set lexicon = loadLexiconFromFile(lexiconFile);
                   final JFrame frame = new JFrame("Test");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   JTextPane textArea = new JTextPane();
                   PowerEditor powerEditor = new PowerEditor(lexicon, frame, textArea);
                   JScrollPane scrollpane = new JScrollPane(powerEditor);
                   scrollpane.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10),
                                                                     BorderFactory.createBevelBorder(BevelBorder.LOWERED)));
                   frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                             System.exit(0);
                   frame.setContentPane(scrollpane);
                   SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                             frame.setSize(500, 500);
                             frame.setVisible(true);
              } catch (IOException e) {
                   e.printStackTrace();

  • Problems with Popups

    Hi,
    I'm having problems trying to use Popups. Not as in JPopupMenu, but a custom popup. I'm writing an application which lets you upload photos to Facebook. I want the 'tagging' part to work in pretty much the same way as it does on the Facebook website: you click on the image, a box pops up with a list of your friend's names and you can type into a text box and narrow the list down or scroll through, that kind of thing.
    Anyway, it's all working pretty well, except for a rather strange problem: when the popup appears and goes outside of the parent window, you can't enter any text into the JTextField. It's as if it was made read-only. You can still click on the JList items and select friends though, which seems strange?! It's just as if the text field can't gain focus when the popup panel goes outside of the frame - when it's inside the frame, there aren't any problems.
    The code works like this: I've created a class called AbstractPopup (which borrows quite heavily from JPopupMenu) - you can see it here:
    http://fb-photo-uploader.googlecode.com/svn/trunk/src/main/java/uk/me/phillsacre/uploader/gui/utils/AbstractPopup.java
    This is the bit that creates the javax.swing.Popup:
         private Popup getPopup()
              if (null != _popup)
                   _popup.hide();
                   _popup = null;
              PopupFactory popupFactory = PopupFactory.getSharedInstance();
              Popup popup = popupFactory.getPopup(getInvoker(), this, _desiredX,
                        _desiredY);
              popup.show();
              return popup;
         }So... anyone have any bright ideas? :-)

    ok, I just managed to find this bug report:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4909116
    Apparently it's "not a bug, it's a feature" :-S

  • Selecting a JList with right-click

    What's the best way for a JList to select its value with a right-click. I plan on bringing up a JPopupMenu on the same right click too.

    You would probably add the standard listener for this sort of thing
    with the addition of selecting the item under the mouse.
    class PopupListener extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                // Make selection
                JList list = (JList) e.getComponent();
                Point p = e.getPoint();
                int index = list.locationToIndex( p );
                if ( index != -1 ) {
                     Rectangle r = list.getCellBounds( index, index );
                     if ( r.x <= p.x && p.x <= r.x + r.width &&
                          r.y <= p.y && p.y <= r.y + r.height )
                         list.setSelectedIndex( index );
                // show popup
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
    }If you want more advanced selection capabalities with the right click,
    I'd look at implementing your own MouseInputHandler which checks for
    isMouseLeftButton() || isPopupTrigger(); see BasicListUI.MouseInputHandler.

  • Installing new keyboard actions to the JList

    Hi I want to install replace the arrow keys and use the numpad keys to go next and previous item in JList also I dont want to show to Popup bar in gui but in the the following code it is not working for the when I install KeyboardActions to the List
    import java.awt.BorderLayout;
    import java.awt.event.KeyEvent;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.KeyStroke;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.plaf.basic.BasicListUI;
    import sun.swing.DefaultLookup;
    public class ListOneItem extends JFrame implements ListSelectionListener {
         private static final long serialVersionUID = 1L;
         public ListOneItem() {
              final String[] numbers = {"one", "two", "three", "four", "five", "six", "seven"};
              final JList list = new JList(numbers);
              list.setVisibleRowCount(1);
              list.setSelectedIndex(0);
              list.addListSelectionListener(this);
              final JScrollPane scrollPane = new JScrollPane(list);
              scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
              scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              getContentPane().add(scrollPane, BorderLayout.NORTH);
              final MyBasicListUI listUI= new MyBasicListUI();
              list.setUI(listUI);
         class MyBasicListUI extends BasicListUI {
              @Override
              public void installKeyboardActions() {
                   // get the input map
                   final InputMap _im = (InputMap) DefaultLookup.get(list, this, "list.ancestorInputMap");
                   // set extra keys for "selectNext" and "selectPrevious" actions
                   _im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, 0), "selectNextRow");
                   _im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, 0), "selectPreviousRow");
                   // install the updated InputMap
                   super.installKeyboardActions();
         public void valueChanged(ListSelectionEvent e) {
              final JList list = (JList) e.getSource();
              list.ensureIndexIsVisible(list.getSelectedIndex());
         public static void main(String[] args) {
              final ListOneItem frame = new ListOneItem();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(200, 200);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }it gives the null pointer exception for the following code
    final MyBasicListUI listUI= new MyBasicListUI();
    list.setUI(listUI);
    where I am trying to add new Keyboard Actions to the JList

    While getting InputMap use key *"List.focusInputMap"* instaed of *"list.ancestorInputMap"* in installKeyboardActions() method.
    final InputMap _im = (InputMap) DefaultLookup.get(list, this, "List.focusInputMap");Only to register new keystrokes for existing actions you don't need to have custom look and feel class. Instead modify the InputMap after list creation.
    import java.awt.BorderLayout;
    import java.awt.event.KeyEvent;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.KeyStroke;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.plaf.basic.BasicListUI;
    import sun.swing.DefaultLookup;
    public class ListOneItemModified extends JFrame implements ListSelectionListener {
         private static final long serialVersionUID = 1L;
         public ListOneItemModified() {
              final String[] numbers = {"one", "two", "three", "four", "five", "six", "seven"};
              final JList list = new JList(numbers);
              list.getInputMap(JList.WHEN_FOCUSED).remove(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
              list.getInputMap(JList.WHEN_FOCUSED).remove(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
              list.getInputMap(JList.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, 0), "selectNextRow");
              list.getInputMap(JList.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, 0), "selectPreviousRow");
              list.setVisibleRowCount(1);
              list.setSelectedIndex(0);
              list.addListSelectionListener(this);
              final JScrollPane scrollPane = new JScrollPane(list);
              scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
              scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              getContentPane().add(scrollPane, BorderLayout.NORTH);
              //final MyBasicListUI listUI= new MyBasicListUI();
              //list.setUI(listUI);
    //     class MyBasicListUI extends BasicListUI {
    //          @Override
    //          public void installKeyboardActions() {
    //               // get the input map
    //               final InputMap _im = (InputMap) DefaultLookup.get(list, this, "list.focusInputMap");
    //               // set extra keys for "selectNext" and "selectPrevious" actions
    //               _im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, 0), "selectNextRow");
    //               _im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, 0), "selectPreviousRow");
    //               // install the updated InputMap
    //               super.installKeyboardActions();
         public void valueChanged(ListSelectionEvent e) {
              final JList list = (JList) e.getSource();
              list.ensureIndexIsVisible(list.getSelectedIndex());
         public static void main(String[] args) {
              final ListOneItemModified frame = new ListOneItemModified();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(200, 200);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

  • My JList does not scroll, even in scroll pane

    This code is not working??
    I am trying this JList to pop up (on a condition) over a JTextArea.
    Its bounds are calculated at run time. Pop up cordiantes will depent upon the caret position.
    PKGlist.setListData(PACKAGE); // PACKAGE is Vector conatining String
    JScrollPane scrollPane = new JScrollPane(PKGlist);
    PKGlist.setAutoscrolls(true);
    pane.add(PKGlist);code for poping up.
    Caret crt=JTA.getCaret(); //JTA is JTextArea
    Point p=crt.getMagicCaretPosition();
    JE.PKGlist.setVisible(true);
    JE.PKGlist.grabFocus();
    JE.PKGlist.setOpaque(true);
    JE.PKGlist.setBackground(new Color(150,150,150));               
    JE.PKGlist.setBounds(p.x+JTA.getX()+10,p.y+JTA.getY()+60,50,100);

    If you want people to answer your questions why don't you post sample code that illustrates your problem.
    Not bits and pieces of code.
    Not 400 lines of code.
    If I understand your problem then the following should help:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PopupList extends JFrame
         JPopupMenu popup;
         JWindow window;
         public PopupList()
              //  Create popup
              String[] items = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
              JList list = new JList( items );
              JScrollPane scrollPane = new JScrollPane( list );
              popup = new JPopupMenu();
              popup.add( scrollPane );
                 window = new JWindow(this);
                 window.getContentPane().add( new JComboBox( items ) );
                 window.pack();
              //  Create text component
              JTextPane textPane = new JTextPane();
              textPane.addMouseListener( new MouseAdapter()
                   public void mouseReleased(MouseEvent e)
                        if (e.isPopupTrigger())
                             popup.show(e.getComponent(), e.getX(), e.getY());
                             // try using a window instead of a popup menu
    //                         window.setLocation(e.getX(), e.getY());
    //                         window.setVisible( true );
              getContentPane().add( textPane );
         public static void main(String[] args)
              throws Exception
              JFrame frame = new PopupList();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setSize(300, 200);
              frame.show();
    }Run the program as is and a popup menu appears. The list is scrollable by using the mouse but not the keyboard. (The keyboard seems to work only when JMenuItems are added to a popup).
    As an alternate solution you could try using a JWindow instead of a popup which will give you full keyboard and mouse control.
    If you want help then make an effort to simplify the problem. Give sample code that people can cut/paste and test. There is absolutely no need to post 400 lines of code. I'm not going to waste my time understanding unnecesary code.

  • Scrollbars in a popup menu

    Hi,
    Anyone please let me know hoe do I make use of a scroll bar in a popup menu. I need to display elements in the form of a popup menu.. and if the number of elements are more than 20, then I need to produce a scroll bar using which the user can scroll to view the other elements in the list.
    Please let me know a solution to this.
    cheers,
    Balu

    JList list = new JList();
    DefaultListModel model = new DefaultListModel();
    for (int i=0; i<20; ++i)
         model.addElement("String " + i);
    list.setModel(model);
    JScrollPane scroller = new JScrollPane();
    scroller.getViewport().add(list);
    JPopupMenu menu = new JPopupMenu();
    menu.add(scroller);
    menu.setPopupSize(100, 150);

Maybe you are looking for