JTextField in a JPopupMenu

I am trying to put a JTextField into a JPopupMenu. The JTextField is unable to gain focus even after calling grabFocus()/requestFocus(). From searching, it seems there is a glitch that each keep on trying to grab the focus from each other. However, I could not find any solution to the problem. Any advice would be helpful.

I thought he was about the ones that popup anywhere on a component via a mouseevent/popup trigger, this was a quickie..
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class TextFieldInMenu {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable(){
            public void run() {
                new TextFieldInMenu().go();
    void go() {
        JFrame f = new JFrame();
        JMenuBar mb = new JMenuBar();
        JMenu menu = new JMenu("test");
        menu.add(new JMenuItem("A popup menu item"));
        menu.add(textfield);
        menu.add(new JMenuItem("Another popup menu item"));
        menu.addMenuListener(new MenuListener(){
            public void menuCanceled(MenuEvent e) {}
            public void menuDeselected(MenuEvent e) {}
            public void menuSelected(MenuEvent e) {
                EventQueue.invokeLater(new Runnable(){
                    public void run() {
                        textfield.grabFocus();
        mb.add(menu);
        popup.add( new JMenuItem("A popup menu item throught a jpopupmenu" ) );
        popup.add( textfield );
        JPanel panel = new JPanel();
        f.getContentPane().add( panel, BorderLayout.CENTER );
        panel.addMouseListener( new MouseHandler() );
        mb.addMouseListener( new MouseHandler() );
        f.setJMenuBar(mb);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize( 640, 480 );
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    JTextField textfield = new JTextField();
    JPopupMenu popup = new JPopupMenu();
    private class MouseHandler extends MouseAdapter
         public void mousePressed(MouseEvent e) {
              System.out.println( "Mouse pressed" );
        maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
        maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e) {
         System.out.println( "maybeShowPopup() called" );
        if (e.isPopupTrigger()) {
            popup.show(e.getComponent(),
                       e.getX(), e.getY());
              textfield.grabFocus();
}Sorry if it's kinda messy, but it's based off BigDaddy's code and it works for me (the textfield gets focus after calling grabFocus() on it in the maybeShowPopup() method in the MouseHandler implementation of MouseAdapter.

Similar Messages

  • Cut,copy,paste in jtextfield

    Hi,
    I gotta JTextField. Now I want to get a popup menu when i right-click it to ask me if i wanna cut, copy or paste using the default os clipboard.
    can anyone suggest me any helpful url ?

    Clipboard operations such as copy, cut and paste are very easy to perform on a JTextField. Just use the JTextField's void cut(), copy() and paste() methods! That's all there is to it.
    In this demo I wrote, I've shown how to use these methods, and how to create a JPopupMenu menu that appears when the user right-clicks on the JTextField, showing the three clipboard functions.
    Enjoy!
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ClipboardDemo extends JFrame implements ActionListener {
         JPanel mainPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
         JLabel descrLabel = new JLabel("Clipboard Demo by Ben James");
         JTextField theTextField = new JTextField(20);
         final JPopupMenu clipboardMenu = new JPopupMenu();
         JMenuItem cutMenuItem = new JMenuItem("Cut");
         JMenuItem copyMenuItem = new JMenuItem("Copy");
         JMenuItem pasteMenuItem = new JMenuItem("Paste");
         public ClipboardDemo() {
              super("Clipboard Demo");
              theTextField.setText("Highlight some text and right-click!");
              cutMenuItem.addActionListener(this);
              copyMenuItem.addActionListener(this);
              pasteMenuItem.addActionListener(this);
              clipboardMenu.add(cutMenuItem);
              clipboardMenu.add(copyMenuItem);
              clipboardMenu.add(pasteMenuItem);
              theTextField.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                             clipboardMenu.show(evt.getComponent(), evt.getX(), evt.getY());
              mainPane.add(descrLabel);
              mainPane.add(theTextField);
              mainPane.setPreferredSize(new Dimension(250,75));
              WindowListener wl = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              setContentPane(mainPane);
              addWindowListener(wl);
              pack();
              setResizable(false);
              setVisible(true);
         public void actionPerformed(ActionEvent evt) {
              Object source = evt.getSource();
              if (source == cutMenuItem) {
                   theTextField.cut();
              if (source == copyMenuItem) {
                   theTextField.copy();
              if (source == pasteMenuItem) {
                   theTextField.paste();
         public static void main(String[] args) {
              ClipboardDemo cd = new ClipboardDemo();
    }

  • Help on dropdown jTextField

    package ui;
    import entity.*;
    import ui.*;
    import database.*;
    import controller.*;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JList;
    public class UpdateForm {
         private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="65,24"
         private JPanel jContentPane = null;
         private JTextField jTextField = null;
         private JTextField jTextField1 = null;
         Guest guest;
         private JTextField text;
         final JPopupMenu menu = new JPopupMenu();
         private ArrayList<Guest> guestList;
         private UpdateController update = new UpdateController();
         private JButton jButton = null;
         * This method initializes jFrame     
         * @return javax.swing.JFrame     
         private JFrame getJFrame() {
              if (jFrame == null) {
                   jFrame = new JFrame();
                   jFrame.setSize(new java.awt.Dimension(531,334));
                   jFrame.setContentPane(getJContentPane());
              return jFrame;
         * This method initializes jContentPane     
         * @return javax.swing.JPanel     
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJTextField(), null);
                   jContentPane.add(getJTextField1(), null);
                   jContentPane.add(getJButton(), null);
              return jContentPane;
         * This method initializes jTextField     
         * @return javax.swing.JTextField     
         private JTextField getJTextField() {
              if (jTextField == null) {
                   jTextField = new JTextField();
                   jTextField.setBounds(new java.awt.Rectangle(49,29,225,20));
                   jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             haha(); // TODO Auto-generated Event stub keyReleased()
              return jTextField;
         public void haha(){
              menu.setVisible(false);
              menu.removeAll();
              String name = jTextField.getText();
              if(name!=null&&name.trim().length()>0){
                   guestList = CreateController.getAllGuest();     
                   for (int i = 0; i <guestList.size(); i++) {
                        JMenuItem item = new JMenuItem(name+" : "+i);
                        item.addActionListener(new CustomActionListener(i));
                        Guest s = new Guest(name, null);
                        UpdateController cc = new UpdateController();
                        menu.add(s.getname());
              menu.show(jTextField, jTextField.getLocation().x-jTextField.getWidth(), jTextField.getLocation().y+jTextField.getHeight());
              jTextField.requestFocus();
         public class CustomActionListener implements ActionListener{
              private int index;
              public CustomActionListener(int index){
                   this.index=index;
              public void actionPerformed(ActionEvent e) {
                   System.out.println(" Index : "+index);
         * This method initializes jTextField1     
         * @return javax.swing.JTextField     
         private JTextField getJTextField1() {
              if (jTextField1 == null) {
                   jTextField1 = new JTextField();
                   jTextField1.setBounds(new java.awt.Rectangle(65,156,194,20));
              return jTextField1;
         * This method initializes jButton     
         * @return javax.swing.JButton     
         private JButton getJButton() {
              if (jButton == null) {
                   jButton = new JButton();
                   jButton.setBounds(new java.awt.Rectangle(395,96,77,30));
                   jButton.setText("get");
                   jButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             getinformation(); // TODO Auto-generated Event stub actionPerformed()
              return jButton;
    public void getinformation(){
         String name = getJTextField().getText();
         System.out.println(name);
         if (name.equals(""))
              JOptionPane.showMessageDialog(null, "Please enter user id!");
         else{
              guest = new Guest(name,null);
              UpdateController update = new UpdateController();
              if (guest.retrieveGuest()){
                   jTextField1.setText(guest.getic_no());
              System.out.println(guest.getic_no());
              else{
                   JOptionPane.showMessageDialog(null, "Record does not exist!");
         public static void main(String[]args){
              UpdateForm updateform = new UpdateForm();
              updateform.getJFrame().setVisible(true);
    i am trying to make the Textfield dropdown the values from my database which colum is name.currently the menu only displays out what i am typing and does not search for related values in the column to whatver i am typing.what corrections are needed so that the jTxtfield will search the values in database column under name and display out related stuffs while i start entering on the jTextField. this is my entity class
    package entity;
    import java.sql.ResultSet;
    import java.util.*;
    import ui.*;
    import controller.*;
    import database.DBController;
    public class Guest {
    private String name;
    private String ic_no;
    private String handphone_no;
    private String dob;
    private String country;
    private String gender;
    private String house_phone;
    private String address;
    private String zipcode;
    private String photo;
    private String countrylist;
    private String genderlist;
    private String dob1;
    private String dob2;
    public Guest(String name,String ic_no,String handphone_no,String dob,String country,String gender,String house_phone,String address,String zipcode,String dob1,String dob2){
         this.name=name;
         this.ic_no=ic_no;
         this.handphone_no=handphone_no;
         this.dob=dob;
         this.country = country;
         this.gender = gender;
         this.house_phone=house_phone;
         this.address = address;
         this.zipcode=zipcode;
         this.dob1=dob1;
         this.dob2=dob2;
    public Guest(String name,String ic_no){
         this.ic_no=ic_no;
         this.name=name;
    public String getname(){
         return name;
    public void setname(String name){
         this.name=name;
    public String getic_no(){
         return ic_no;
    public void setic_no(String ic_no){
         this.ic_no=ic_no;
    public String gethandphone_no(){
         return handphone_no;
    public void sethandphone_no(String handphone_no){
         this.handphone_no=handphone_no;
    public String getdob(){
         return dob;
    public void setdob(String dob){
         this.dob=dob;
    public String getcountry(){
         return country;
    public void setcountry(String country){
         this.country=country;
    public String getgender(){
         return gender;
    public void setgender(String gender){
         this.gender=gender;
    public String gethouse_phone(){
         return house_phone;
    public void sethouse_phone(String house_phone){
         this.house_phone=house_phone;
    public String getaddress(){
    return address;
    public void setaddress(String address){
         this.address=address;
    public String getzipcode(){
         return zipcode;
    public void setzipcode(String zipcode){
         this.zipcode=zipcode;
    public String getphoto(){
         return photo;
    public void setphoto(String photo){
         this.photo=photo;
    public String getcountrylist(){
         return countrylist;
    public void setcountrylist(String countrylist){
         this.countrylist= countrylist;
    public String getgenderlist(){
         return genderlist;
    public void setgenderlist(String genderlist){
         this.genderlist=genderlist;
    public String getdob1(){
         return dob;
    public void setdob1(String dob1){
         this.dob1=dob1;
    public String getdob2(){
         return dob2;
    public void setdob2(String dob2){
         this.dob2=dob2;
    public boolean retrieveGuest(){
         boolean success = false;
         ResultSet rs = null;
         DBController db = new DBController();
         db.setUp("database");
         String dbQuery = "SELECT * FROM Guest WHERE name ='";
         dbQuery += name + "'" ;
         rs = db.readRequest(dbQuery);
         try{
              if (rs.next()){
                   ic_no = rs.getString("ic_no");
                   success = true;
         }catch (Exception e) {
              e.printStackTrace();
         db.terminate();
         return success;
    }

    You really need to follow AndrewThompson64 recommendation to use code tags,
    some indentation and comments would also be good, and put the explanation before the code.
    Your question is too difficult to read and understand!
    Are you trying to develop some kind of web browser AddressBar GUI ?
    That shows entries related to what the user is typing on the field, and also allows the user the select an item on the dropdown?
    If that's your case, I'll post an example code I developed here.

  • Child JWindow containing JTextField takes focus from JFrame

    I have a bit of a unique problem.
    I have a JFrame as the main application window. I then create a JWindow with a JTextField that I would like to use as a Popup Palette. The problem is that when I click in the text box, the title bar of the JFrame changes it's appearance because the focus is now on the text box in the JWindow.
    If I use setFocusableWindowState(false) on the JWindow then the title bar of the JFrame does not change(which is the behaviour I want), but I cannot type in the JTextField.
    I understand why this is happening. The JTextField needs to have focus in order to recieve input and because it is in the JWindow, the JWindow takes the focus away from the JFrame.
    Does anyone know how I can make it so the JFrame Title Bar does not change appearance when the JTextField in the JWindow gets focus?
    The only thing that I can think of, is to somehow change the JFrame Look & Feel so that the title does not change appearance when the JFrame looses focus. I have no idea how to do that though.
    If you are wondering why I need this, it is because I need a JTextField to display on top of a Heavyweight component. I want it to appear as if it is part of the same window. Having the title bar of the JFrame change when you click in the textbox kind of destroys the illusion that it is part of the heavyweight component.
    Also, if you know of any other ways to get the JTextField to display and work on top of a Heavyweight component then I would appreciate that as well.
    Here is an example that you can run to see the behaviour. You can try it with the setFocusableWindowState line both uncommented and commented out.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JWindow;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class TestFocus implements Runnable {
        private JFrame frame;
        private JWindow popup;
        public void run() {
            //Create a new Frame
             frame = new JFrame("Frame Test");
             JButton but = new JButton("Does Nothing");
            frame.getContentPane().add(but);
            frame.setPreferredSize(new Dimension( 500, 500 ));
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            //Create a JWindow with a JTextField
            popup = new JWindow( frame );
            JPanel p = new JPanel(new BorderLayout());
            JTextField txt = new JTextField();
            p.add( txt, BorderLayout.NORTH );
            JButton but2 = new JButton("Also does nothing");
            p.add(but2, BorderLayout.SOUTH);
            popup.getContentPane().add(p);
            popup.setLocation( frame.getLocation().x + 50, frame.getLocation().y + 50 );
            popup.pack();
            //Proper title behaviour if I have this statement
            //but then I can't type in the text box.
            //popup.setFocusableWindowState(false);
            popup.setVisible(true);
        public static void main(String[] args) {
            try {
                System.setProperty("sun.java2d.noddraw", "true");
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception e) {
            SwingUtilities.invokeLater(new TestFocus());
    }Thanks,
    Jeff

    The code works fine on XP using JDK1.4.2, maybe its a version/platform issue check the bug database.
    -> if you know of any other ways to get the JTextField to display and work on top of a Heavyweight component
    You could try using
    JPopupMenu.setDefaultLightWeightPopupEnabled(false)and then add the JTextField to a jPopupMenu instead of a JWindow (although behind the scenes I think it will use a JWindow as the popup, so it may not solve the problem either if it is a version/platform issue).

  • Highlight text in TextField

    I am creating an autocomplete feature for a school project using JAVA. I have created a TextField with a keyListener to lister for keypresses. After the keypress, I search a list for possible matches; stopping on the first match which is then st to the TextField. I have one problem I am trying to fix. I would like to highlight all the text after the caret position. However, when you highlight the text it moves the caret position to the end of the selection. If I set it back to the position th user is typing it deselects my selected text.
    How can I highlight text after teh caret position in a TextField?

    hi,
    try to search the forum and web by the words autocompleting JComboBox, a lot of hints will appear. As you probably know, the JComboBox consists of the JTextField, JButton and JPopupMenu, so autocompletition will be nearly the same.
    This site si very good, I think:
    http://www.orbital-computer.de/JComboBox/
    Good luck, hope I help you
    L.P.

  • Hi All... Need ur help in this.

    Iam desiging pop-up window, where it takes text from one textfield and pastes into other.. here is the code.. im not able to finish the code of properly, as im vry new to java.. plz help on this. Thanks in advance..
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MyPopUp extends JApplet implements ActionListener
         Component fSelectedComponent;
         JFrame frame;
         JPopupMenu popup;
         JMenuItem one,two,three;
         Container cp;
         MouseAdapter fAdapter;
         JTextField source,dest;
         public void init()
              JFrame frame = new JFrame("Popup Example");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cp = getContentPane();
              source = new JTextField();
              dest = new JTextField();
              popup = new JPopupMenu();
              one = new JMenuItem("Add To ClipBoard");
              one.addActionListener(this);
              two = new JMenuItem("Confirm");
              two.addActionListener(this);
              three = new JMenuItem("Reset");
              three.addActionListener(this);
              popup.add(one);
              popup.add(two);
              popup.add(three);
              cp.add(source,BorderLayout.NORTH);
              cp.add(dest,BorderLayout.SOUTH);
         MouseListener mouseListener = new MouseAdapter() {
         private void showIfPopupTrigger(MouseEvent mouseEvent) {
         if (mouseEvent.isPopupTrigger()) {
         popup.show(mouseEvent.getComponent(),
                        mouseEvent.getX(),
                        mouseEvent.getY());
         public void mousePressed(MouseEvent mouseEvent) {
         showIfPopupTrigger(mouseEvent);
         public void mouseReleased(MouseEvent mouseEvent) {
         showIfPopupTrigger(mouseEvent);
         frame.addMouseListener (mouseListener);
         frame.setSize(350, 250);
         frame.setVisible(true);
         public void actionPerformed(ActionEvent me)
              if(me.getSource() == one)
                   dest.setText((source.getText()).toString());
                   source.setText("Clicked on Add to ClipBoard");
              if(me.getSource() == two)     {
                   dest.setText((source.getText()).toString());
                   source.setText("Confirm");
              if(me.getSource() == three)     {
                   dest.setText((source.getText()).toString());
                   source.setText("Reset");
    }

    What exactly are you trying to do here? didn't get it!!

  • HistoryTextField (Discussion)

    Has anyone well versed in swing/awt default focus management or popupmenu? Maybe you can help me to improve HistoryTextField i have written...
    I try to create a simple history textfield, which consists of a JTextfield and a JPopupMenu, and using an arraylist for caching the textfield's previous entered value. HistoryTextField also implements FocusListener and Documentlistener so that it will can cache the entered value, as well as update the content(menuitem) of the popupmenu.
    note that i didn't use JPopupMenu's show(Component comp, int x, int y) method as i don't want popupmenu, upon showing up, grabbing focus from the textfield. i set popupmenu.setfocusable(false), and popupmenu.setVisible(true/false) to accomplish this, as stated in http://developer.java.sun.com/developer/bugParade/bugs/4632782.html
    everything works fine until when user attempt to make a selection to one of the menuitems in popupmenu, the popupmenu disappears as expected but fail to transfer focus back to textfield, eventhough i have try to have textfield to requestFocus().
    i suspect it's because i had the popupmenu.setFocusable(false)... i think when making selection, the menuitems in the popupmenu gain focus, after that it probably transfers the focus to their container, that is the popupmenu, and unfortunately the popupmenu cannot be focused anymore. so everything just hang there, no component can gain the focus because of this missing "link". To gain focus, i have to do the lousy manual minimise and maximise JFrame method :p
    i have overcome this problem by implementing mouselistener, and do a "twist" at mouseEntered() method, where i switch off the popupmenu and instantly switch it on again using show() method just before user want to make a selection at the popupmenu. the outcome is ok but still have some bugs yet. apparently
    i post the source code at below, everyone is welcome to evaluate it. any idea or comment are welcomed.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.ArrayList;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    import javax.swing.JTextField;
    import javax.swing.JPopupMenu;
    import javax.swing.JMenuItem;
    import javax.swing.text.Document;
    import javax.swing.FocusManager;
    * History text Field
    * @author Chong Jin Chun, [email protected]
    * @since 1.0
    public class HistoryTextField extends JTextField implements DocumentListener, FocusListener, ActionListener, MouseListener
    private ArrayList history = null;
    private JPopupMenu popupMenu = null;
    private String currentText = "";
    private String selectedText = "";
    private String tempText = null;
    private JMenuItem emptyMenuItem = null;
    private JMenuItem tempMenuItem = null;
    private boolean textInput = true;
    private int popupEntrySize = 0;
    private int maxPopupEntrySize = 5;
    private int maxHistorySize = 50;
    * Constructs a new HistoryTextField.
    * @since 1.0
    public HistoryTextField()
    super();
    init();
    * Constructs a new HistoryTextField that uses the given text storage model and the given number of columns.
    * @param doc Description of the Parameter
    * @param text Description of the Parameter
    * @param columns Description of the Parameter
    * @since 1.0
    public HistoryTextField(Document doc, String text, int columns)
    super(doc, text, columns);
    init();
    * Constructs a new empty HistoryTextField with the specified number of columns.
    * @param columns Description of the Parameter
    * @since 1.0
    public HistoryTextField(int columns)
    super(columns);
    init();
    * Constructs a new HistoryTextField initialized with the specified text.
    * @param text Description of the Parameter
    * @since 1.0
    public HistoryTextField(String text)
    super(text);
    init();
    * Constructs a new HistoryTextField initialized with the specified text.
    * @param text Description of the Parameter
    * @param columns Description of the Parameter
    * @since 1.0
    public HistoryTextField(String text, int columns)
    super(text, columns);
    init();
    * Initialise
    * @since 1.0
    public void init()
    history = new ArrayList();
    popupMenu = new JPopupMenu();
    addMouseListener(this);
    getDocument().addDocumentListener(this);
    addFocusListener(this);
    * Set maximum history cache size, default is 50
    * @param maxHistorySize The new maxHistorySize value
    * @since 1.0
    public void setMaxHistorySize(int maxHistorySize)
    this.maxHistorySize = maxHistorySize;
    * Set maximum number of JMenuItems should be shown, default is 5
    * @param maxPopupEntrySize The new maxPopupEntrySize value
    * @since 1.0
    public void setMaxPopupEntrySize(int maxPopupEntrySize)
    this.maxPopupEntrySize = maxPopupEntrySize;
    * Get maximum history cache size, default is 50
    * @param maxHistorySize Description of the Parameter
    * @return The maxHistorySize value
    * @since 1.0
    public int getMaxHistorySize(int maxHistorySize)
    return maxHistorySize;
    * Get maximum number of JMenuItems should be shown, default is 5
    * @param maxPopupEntrySize Description of the Parameter
    * @return The maxPopupEntrySize value
    * @since 1.0
    public int getMaxPopupEntrySize(int maxPopupEntrySize)
    return maxPopupEntrySize;
    * Clearing the history cache
    * @since 1.0
    public void clearHistory()
    history.clear();
    * Show History, which is actually showing JPopupMenu
    * @since 1.0
    public void showHistory()
    currentText = getText();
    //reset popupMenu
    for (int i = popupEntrySize - 1; i > -1; i--)
    popupMenu.remove(i);
    popupEntrySize = 0;
    //search history
    if (!history.isEmpty() && !currentText.equals("") && !currentText.equals(selectedText))
    for (int i = history.size() - 1; i > -1; i--)
    tempText = (String) history.get(i);
    if ((tempText.startsWith(currentText)) && (!tempText.equals(currentText)))
    popupEntrySize++;
    tempMenuItem = popupMenu.add(tempText);
    tempMenuItem.addActionListener(this);
    tempMenuItem.addMouseListener(this);
    if (popupEntrySize == maxPopupEntrySize)
    break;
    //To show or not to show
    if (popupEntrySize > 0)
    popupMenu.setPopupSize(getWidth(), getHeight() * popupEntrySize);
    popupMenu.setLocation(getLocationOnScreen().x, getHeight() + getLocationOnScreen().y);
    popupMenu.setBackground(getBackground());
    popupMenu.setFocusable(false);
    popupMenu.repaint();
    popupMenu.setVisible(true);
    else
    popupMenu.setFocusable(false);
    popupMenu.repaint();
    popupMenu.setVisible(false);
    requestFocus();
    * Hide history, which is actually hide the JPopupMenu
    * @since 1.0
    public void hideHistory()
    if (popupMenu.isVisible())
    popupMenu.setFocusable(false);
    popupMenu.setVisible(false);
    * Invoked when the input for this component is modified
    * @param e Description of the Parameter
    * @since 1.0
    public void changedUpdate(DocumentEvent e)
    showHistory();
    * Invoked when the input for this component is modified
    * @param e Description of the Parameter
    * @since 1.0
    public void insertUpdate(DocumentEvent e)
    showHistory();
    * Invoked when the input for this component is modified
    * @param e Description of the Parameter
    * @since 1.0
    public void removeUpdate(DocumentEvent e)
    showHistory();
    * Invoked when the focus of this component is gained/regained
    * @param e Description of the Parameter
    * @since 1.0
    public void focusGained(FocusEvent e)
    showHistory();
    * Invoked when the focus of this component is lost
    * @param e Description of the Parameter
    * @since 1.0
    public void focusLost(FocusEvent e)
    if (!getText().equals(""))
    if (history.indexOf(getText()) == -1)
    if (history.size() == maxHistorySize)
    history.remove(0);
    else
    history.remove(history.indexOf(getText()));
    history.add(getText());
    hideHistory();
    * Invoked when one of the JMenuItem(s) in JPopupMenu is selected
    * @param e Description of the Parameter
    * @since 1.0
    public void actionPerformed(ActionEvent e)
    tempMenuItem = (JMenuItem) e.getSource();
    setText(selectedText = tempMenuItem.getText());
    * Invoked when the mouse button has been clicked (pressed and released) on this component.
    * @param e Description of the Parameter
    * @since 1.0
    public void mouseClicked(MouseEvent e)
    if (e.getSource().equals(this))
    requestFocus();
    * Invoked when the mouse enters one of the JMenuItem(s) in JPopupmenu.
    * @param e Description of the Parameter
    * @since 1.0
    public void mouseEntered(MouseEvent e)
    if (e.getSource() instanceof JMenuItem)
    if (!popupMenu.isFocusable())
    popupMenu.setFocusable(true);
    popupMenu.setVisible(false);
    popupMenu.show(this, 0, getHeight());
    ((JMenuItem)e.getSource()).requestFocus();
    * Invoked when the mouse exits this component.
    * @param e Description of the Parameter
    * @since 1.0
    public void mouseExited(MouseEvent e) { }
    * Invoked when a mouse button has been pressed on this component.
    * @param e Description of the Parameter
    * @since 1.0
    public void mousePressed(MouseEvent e)
    if (e.getSource().equals(this))
    requestFocus();
    * Invoked when a mouse button has been released on this component.
    * @param e Description of the Parameter
    * @since 1.0
    public void mouseReleased(MouseEvent e)
    if (e.getSource().equals(this))
    requestFocus();

    I just thought this may be a more direct way to notify about the user, not just the post.
    It is. Or it used to be. To be honest, I have no idea if that's true anymore. Either way, I was just responding to let you know that this topic has been broached in other quarters, as well, and that you are not alone in your concerns, etc.
    And yes it is, of course, up to the Hosts to decide what to do; I didn't mean to say anything otherwise.
    I believe that you allowed that the Hosts will decide what they want to do about this and/or similar situations in your OP. My mentioning it was more didactic, and intended for other members who may be reading this topic, but who are not as familiar with how things work around here as you and I.
    I've seen this forum used for notifying the Hosts of a user in this way, so I thought it wouldn't be out of the norm to do so.
    You are correct. This forum is sometimes used for exactly that purpose. Even so, many people would agree that using the 'Report this post' link is a more discreet way of drawing attention to problem posts and/or members. Posting about people and their posts publicly sometimes invites new problems and exacerbates existing ones, especially wrt aggressive or angry posters, but that's not to suggest that this will be the case in the present situation.
    I didn't mean to be against any rules, I just thought this may be a more effective way, in addition to "Report this post".
    You haven't broken any rules that I'm aware of. Again, I responded to your topic to inform you that your concerns are shared by other people and raised in other quarters, as well.
    Good luck!

  • Problem with InputVerifier and JPopupMenu

    Hello, I have a problem related to the usage of InputVerifier and JPopupMenu.
    Consider the following scenario:
    - A frame composed of two components: a JTextField and a JComboBox
    - An InputVerifier that was set in the JComboBox (and in its associated JTextComponent)
    - A JPopupMenu which is enabled by a right mouse click over the components of the frame.
    The verify() method of the InputVerifier class is executed every time the focus is on the JComboBox and is requested by other component.
    Suppose that the focus is on the JComboBox, and a right mouse click is executed over this components. In summary, we have:
    1) The method verify() of the InputVerifier associated to the JComboBox is executed
    2) The focus changes from the JTextComponent (associated to the JComboBox) to the JRootPane (associated to the JTextComponent (that is associated to the JPopupMenu)).
    Now suppose that, the user clicks in the JTextField component (note that the JPopupMenu is visible and has the focus). What happens is that the focus goes from the JRootPane -> JTextComponent (associated to the JComboBox) -> JTextField.
    Despite the focus flow through the JTextComponent, the Swing plattaform, when executing the runInputVerifier() in the JComponent context, get the JRootPane component as the focusOwner instead of the JTextComponent.
    In this way, the Swing platform tries to invoke the InputVerify of the JRootPane (that is set with "null"), and the JComboBox InputVerifier is not executed as expected.
    It works as if the focus is flowing from the JRootPane directly to the JTextField.
    However, if the user clicks on the JComboBox before clicking in the JTextField, the Swing platform executes the correct InputVerifier, i.e., the one associated to the JComboBox (actually, the one associated to the JTextComponent).
    Any thoughts to solve this problem?
    Thanks

    A plus information, I am using jdk1.5.0_22.

  • Focus problem when JPopupMenu is shown

    I have compiled and ran the following 'JPopupTest.java' in JDK 1.4.1 on Windows. Kindly conduct the two tests as given below
    First Test :
    ============
    The class shows an editable JComboBox and a JButton when visible. Now click the down-arrow button of the JComboBox and make the drop-down popup visible. Then click on the "OK" button while the popup is visible. The popup gets hidden and a dialog is displayed as it should be.
    Second Test :
    =============
    Run the appilcation again. This time type something in the editable textfield of the JComboBox. A custom JPopupMenu with the text "Hello World" would be visible. Then click on the "OK" button while the popup is visible. The expected dialog is not shown. The custom JPopupMenu gets hidden. Now click on "OK" button again. The dialog is visible now.
    My Desire :
    ===========
    When I click on the "OK" button in the "Second Test" the JPopupMenu should get hidden and the dialog gets displayed (as it happens for the "First Test") in one click.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    import java.util.*;
    public class JPopupTest extends JPanel implements DocumentListener, ActionListener
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         JPopupMenu jpopupmenu;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         public JPopupTest()
            vec = new Vector();
               vec.addElement("One");
            vec.addElement("Two");
            vec.addElement("Three");
            vec.addElement("Four");
            vec.addElement("Five");
            vec.addElement("Six");
            vec.addElement("Seven");
            vec.addElement("Eight");
            vec.addElement("Nine");
            vec.addElement("Ten");
            jcombobox = new JComboBox(vec);
            jcombobox.setEditable(true);
            _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
            jtextfield = ((JTextField) _bcbe.getEditorComponent());
            jtextfield.getDocument().addDocumentListener(this);
            add(jcombobox);
            button = new JButton("OK");
            button.addActionListener(this);
            add(button);
            jpopupmenu = new JPopupMenu();
            jpopupmenu.add("Hello World");
         public void insertUpdate(DocumentEvent e)  {changedUpdate(e);}
         public void removeUpdate(DocumentEvent e)  {changedUpdate(e);}
            public void changedUpdate(DocumentEvent e)
            if(!jpopupmenu.isVisible())
            jpopupmenu.show(jcombobox, 0, jcombobox.getHeight());
            jtextfield.requestFocus();
         public void actionPerformed(ActionEvent e)
            JOptionPane.showMessageDialog(this, "OK button was pressed");
         public static void main(String[] args)
            JPopupTest test = new JPopupTest();
            JFrame jframe = new JFrame();
            jframe.getContentPane().add(test);
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jframe.setSize(200,100);
            jframe.setVisible(true);

    See the code below with auto complete of text. When button is pressed, still TF gets focus after JOptionPane dialog is closed.
    -Pratap
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    public class JPopupTest extends JPanel implements ActionListener {
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         MyComboUI comboUi = new MyComboUI();
         public JPopupTest() {
              vec = new Vector();
              vec.addElement("One");
              vec.addElement("Two");
              vec.addElement("Three");
              vec.addElement("Four");
              vec.addElement("Five");
              vec.addElement("Six");
              vec.addElement("Seven");
              vec.addElement("Eight");
              vec.addElement("Nine");
              vec.addElement("Ten");
              jcombobox = new JComboBox(vec);
              jcombobox.setEditable(true);
              jcombobox.setUI(comboUi);
              add(jcombobox);
              button = new JButton("OK");
              button.addActionListener(this);
              add(button);
              _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
              jtextfield = ((JTextField) _bcbe.getEditorComponent());
              jtextfield.addCaretListener(new CaretListener() {
                        public void caretUpdate(CaretEvent e) {
                             if (!jcombobox.isPopupVisible() && jtextfield.isShowing() &&
                                       jtextfield.hasFocus()) {
                                  jcombobox.showPopup();
                             String text = jtextfield.getText().toLowerCase();
                             int index = -1;
                             for (int i = 0; i < jcombobox.getItemCount(); i++) {
                                  String item = ((String) jcombobox.getItemAt(i)).toLowerCase();
                                  if (item.startsWith(text)) {
                                       index = i;
                                       break;
                             if (index != -1) {
                                  comboUi.getList().setSelectedIndex(index);
                             } else {
                                  comboUi.getList().clearSelection();
                   jtextfield.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent e) {
                             if (e.getKeyCode() == e.VK_ENTER) {
                                  Object value = comboUi.getList().getSelectedValue();
                                  jcombobox.setSelectedItem(value);
                                  jcombobox.hidePopup();
         public void actionPerformed(ActionEvent e) {
              JOptionPane.showMessageDialog(this,"OK button was pressed");
              jtextfield.requestFocus();
         public static void main(String[] args) {
              JPopupTest test = new JPopupTest();
              JFrame jframe = new JFrame();
              jframe.getContentPane().add(test);
              jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jframe.setSize(200,100);
              jframe.setVisible(true);
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList() {
                   return listBox;

  • JTabbedPane,JTable in JPopupMenu

    Hai,
    In my applet, I have added JTabbedPane and JTable in JPopupmenu just like JPanel using Java 1.3. It works fine. Now when I run this applet using Java 1.5 plugin, if I click on that JTable or JTabbedPane over JPopupmenu it closed automatically. It works fine in Java 1.4 also.
    Any ideas...?

    Hai,
    Finally I got solution for this. If I use
    show(Component invoker, int x, int y) method it gives problem. So
    I have changed my code using setLocation(int x,int x) and then
    setVisible(true). It works fine.
    But Now I have got another problem. If I add JTextField over JPopupMenu, I couldn't edit that textfield.
    Anybody having solution for this?

  • Focus problem in 1.4_2 after JPopupMenu show

    Hi, there:
    I have an application, with a JTextField when that textfield gained focus, a popup menu is shown, and when it lost focus, the popup menu is hidden.
    My focus listener class is listed below, where popup is JPopupMenu, and function displayPopup() is just to call show() in JPopupMenu:
         class MyFocusListener extends FocusAdapter {
              public void focusGained(FocusEvent e) {
                   System.out.println("focus gained.............");
                   displayPopup();
              public void focusLost(FocusEvent e) {
                   System.out.println("focus lost ..............");
                   popup.setVisible(false);
         }Everything works fine in jdk 1.3 version. In jdk1.4_2 version, I met following issues:
    1. whenever the text field gained the focus, the application keeps calling "focusGained()", and "focusLost()" functions endlessly (it seems the system keeps sending those focus events endlessly);
    2. if I removed that "popup.setVisible(false)" in focusLost, then, it seems no other component can gain the focus anylonger.
    So, very appreciated if anyone can give me some help, is that a bug in 1.4.2 or is there any way to work around?
    Thanks a lot
    David

    The reason is that in 1.4.2 each time you show a popup over a text field, it trades focus back and fourth with the text field a few times (2-3 times) before it is fully shown.
    That means you gain focus... diaplay a popup -> which fires 2-3 more gain/lost focus -> and on each of those, you show a popup -> infinite loop.
    Here is the overall tip: Don't try to show/hide popups based on foucs events. Make them controlled by something else, like clicking events.
    If you must do this, you can use a timer to avoid the issue. Just make sure you are using showPopup(Component,x,y) in your displayPopup() method!
    class MyFocusListener extends FocusAdapter {
      long lastTimeGainedFocus = -1L;
      public void focusGained(FocusEvent e) {
        long currentTime = System.getCurrentTimeMilliseconds();
        if(lastTimeGainedFocus == -1L || currentTime - lastTimeGainedFocus > 100) {
          displayPopup();
        lastTimeGainedFocus = currentTime;
      public void focusLost(FocusEvent e) {
         // do nothing here... popup should hide itself
    }

  • JPopupMenu with a JScrollPane

    I have couple of questions
    1. I want to add a JScrollPane to JPopupMenu, doing this would not make the JPopupMenu visible. Is this doable?
    2. this is not related to question 1
    I have a JPOpupMenu with JMenuItems. When I select one of items and the item selected , I append the String to a JTextArea.
    The focus goes back to th beginning of the textArea, I want the focus to be at the end of string that is appended to the textArea.
    thanx

    I might sounding dense here, but I tried all the suggestions, it does not help. The textArea does not even get displayed.
    Also I noticed another thing, the JtextArea is registered with a mouseListener. But when I right click on JTextField , I get teh popup. Which is strange.
    I have attached the code with the above suggestions.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TextChooserDemo extends JFrame{
         private JTextField field;
         private JLabel label1;
         private JLabel label2;
         private JPanel aPanel ;
         private JPanel bPanel;
         private JTextArea textArea;
        private TextChooser chooser;
        public TextChooserDemo() {
            initComponents();
            chooser=new TextChooser(this,textArea);
        private void initComponents() {
              field = new JTextField(20);
              label1 = new JLabel("Label1");
              textArea = new JTextArea();
              aPanel = new JPanel();
              aPanel = new JPanel();
              aPanel.setLayout(new BorderLayout());
              aPanel.add(label1, BorderLayout.WEST);
              aPanel.add(field, BorderLayout.CENTER);
              label2 = new JLabel("Label2");
              bPanel = new JPanel();
              bPanel.setLayout(new BorderLayout());
              bPanel.add(label2, BorderLayout.WEST);
              aPanel.add(textArea, BorderLayout.CENTER);
            setTitle("Text-Chooser Demo");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            getContentPane().add(aPanel,BorderLayout.NORTH );
            getContentPane().add(bPanel,BorderLayout.CENTER);
            //getContentPane().add(aPanel );
            //getContentPane().add(bPanel);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-500)/2, (screenSize.height-350)/2, 500, 350);
        public static void main(String args[]) {
            new TextChooserDemo().setVisible(true);
    class TextChooser extends JWindow {
        public TextChooser(JFrame parent, JTextArea textArea){
            super(parent);
            this.parent=parent;
            this.textArea=textArea;
            initChooser();
        private void initChooser(){
            textArea.addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent evt) {
                    textAreaMouseReleased(evt);
            popupScrollPane = new JScrollPane();
            popupList = new JList();
            popupList.setModel(new AbstractListModel() {
                String[] strings = { "java ", "is ", "cool ", "and ", "nice ", "to ", "have ", "with ", "no ", "error ", ".\n" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    popupList.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent evt) {
    popupListAction(evt);
    popupScrollPane.setViewportView(popupList);
    getContentPane().add(popupScrollPane);
    private void popupListAction(ListSelectionEvent evt) {
    if (evt.getValueIsAdjusting() == false) {
    textArea.append((String)popupList.getSelectedValue());
    try{
    textArea.setCaretPosition(textArea.getLineEndOffset(textArea.getLineCount()-1));
    }catch(BadLocationException ex){ex.printStackTrace();}
    setVisible(false);
    textArea.requestFocus();
    private void textAreaMouseReleased(MouseEvent evt) {
    Point pnt = evt.getPoint();
    int x = (int)pnt.getX()+(int)parent.getX();
    int y = (int)pnt.getY()+(int)parent.getY()+20;
    if( !contains(x,y) ){
    setVisible(false);
    if(evt.isPopupTrigger()){
    setBounds(x,y,200,100);
    setVisible(true);
    private JFrame parent;
    private JTextArea textArea;
    private JScrollPane popupScrollPane;
    private JList popupList;
    thnx again!!!

  • Custom JButton for JPopupMenu

    I need to make a custom PopupMenu Button . This button needs to be added to the custom JPopupmenu . This custom button must have the look and feel of a typical menu item. Basically it should have a typical features of a checkboxmenuitem where I have an check.jpg for check and uncheck of the button. How do I reproduce the look and feel of a menuitem. What changes do i make in the below code. Basically no border, button press should not be there. It should not look like we are adding JButtons to the user
    import javax.swing.Action;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.border.EmptyBorder;
    public class XCheckedButton
            extends JButton {
        private boolean flag;
        private ImageIcon checkedIcon;
        public XCheckedButton() {
            super();
        public XCheckedButton(Action a) {
            this();
            setAction(a);
        public XCheckedButton(Icon icon) {
            super(icon);
        public XCheckedButton(String text, Icon icon) {
            super(text, icon);
        public XCheckedButton(String text) {
            super(text);
         public ImageIcon getCheckedIcon() {
              return checkedIcon;
         public void setCheckedIcon(boolean state) {
              this.checkedIcon = checkedIcon;
    }

    Thanks a lot. Here are my 2 java files and right below is the probelm I am facing when USing JMenuItems. Thats the reason why i switched over to JButtons.
    JframePopupMenu.java
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class JFramePopupMenu extends JFrame  {
         private static final long serialVersionUID = 1;
         private JPanel jContentPane = null;
         private JButton jbnPopup = null;
         private JTextField jtfNumOfMenus = null;
         private JLabel lblNumElem = null;
         JTextArea output;
        JScrollPane scrollPane;
        String newline = "\n";
        ScrollablePopupMenu scrollablePopupMenu = new ScrollablePopupMenu(JFramePopupMenu.this.getGraphicsConfiguration());
         private JButton getBtnPopup() {
              if (jbnPopup == null) {
                   jbnPopup = new JButton();
                   jbnPopup.setText("View Popup");
                   jbnPopup.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             int n = Integer.parseInt(getTxtNumElem().getText());
                             JCheckBoxMenuItem cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
                             cbMenuItem.addActionListener(new ActionListener(){
                                  public void actionPerformed(ActionEvent e) {
                                       System.out.println( e );
                                       scrollablePopupMenu.hidemenu();
                           cbMenuItem.setMnemonic(KeyEvent.VK_C);
                           scrollablePopupMenu.add(cbMenuItem);
                             for (int i=0;i<n;i++){
                                  JMenuItem xx = new JMenuItem(" JMenuItem  " + (i+1));
                                       xx.addActionListener(new ActionListener(){
                                       public void actionPerformed(ActionEvent e) {
                                            System.out.println( e );
                                            scrollablePopupMenu.hidemenu();
                             //     scrollablePopupMenu.add(new JButton(" JMenuItem  " + (i+1)));
                                  scrollablePopupMenu.add(xx);
                             scrollablePopupMenu.show(jbnPopup, jbnPopup.getWidth()*3, 0);
              return jbnPopup;
         private JTextField getTxtNumElem() {
              if (jtfNumOfMenus == null) {
                   jtfNumOfMenus = new JTextField();
                   jtfNumOfMenus.setColumns(3);
                   jtfNumOfMenus.setText("60");
              return jtfNumOfMenus;
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        JFramePopupMenu thisClass = new JFramePopupMenu();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
         public JFramePopupMenu() {
              super();
              initialize();
         private void initialize() {
              this.setSize(274, 109);
              this.setContentPane(getJContentPane());
              this.setTitle("Scrollable JPopupMenu");
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   lblNumElem = new JLabel();
    //               lblNumElem.setText("N�mero de elementos del Men�");
                   FlowLayout flowLayout = new FlowLayout();
                   flowLayout.setHgap(8);
                   flowLayout.setVgap(8);
                   jContentPane = new JPanel();
                   jContentPane.setLayout(flowLayout);
                   jContentPane.add(getBtnPopup(), null);
                   jContentPane.add(lblNumElem, null);
                   jContentPane.add(getTxtNumElem(), null);
              return jContentPane;
    ScrollablePopupMenu.java
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsConfiguration;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JSeparator;
    public class ScrollablePopupMenu extends JPopupMenu {
         private static final long serialVersionUID = 1;
         private JPanel panelMenus = null;
         private JScrollPane scroll = null;
         public ScrollablePopupMenu(GraphicsConfiguration gc) {
              super();
              scroll = new JScrollPane();
              panelMenus = new JPanel();
              panelMenus.setLayout(new GridLayout(0,1));
              scroll.setViewportView(panelMenus);
              scroll.setBorder(null);
              scroll.setMaximumSize(new Dimension(scroll.getMaximumSize().width,
                        this.getToolkit().getScreenSize().height -
                        this.getToolkit().getScreenInsets(gc).top -
                        this.getToolkit().getScreenInsets(gc).bottom - 4));
              super.add(scroll);
         public void show(Component invoker, int x, int y) {
              this.pack();
              panelMenus.validate();
              int maxsize = scroll.getMaximumSize().height;
              int realsize = panelMenus.getPreferredSize().height;
              int sizescroll = 0;
              if (maxsize < realsize) {
                   sizescroll = scroll.getVerticalScrollBar().getPreferredSize().width;
              scroll.setPreferredSize(new Dimension(
                        scroll.getPreferredSize().width + sizescroll,
                        scroll.getPreferredSize().height));
              this.setLocation( x, y);
              this.setVisible(true);
         public void hidemenu(){
              if(this.isVisible()){
                   this.setVisible(false);
         public JMenuItem add(JMenuItem menuItem) {
              panelMenus.add(menuItem);
              return menuItem;
         public void addSeparator() {
              panelMenus.add(new JSeparator());
    Problem 1: Not able to Scroll down when frame is Large
    My application is a large frame and when I invoke the JPopupMenu on it I am not able to scroll.
    In the example application also I found the same problem when I maximize the frame. I am able to see the JPopupMenu but not able to scroll on it.

  • How to make JPopupMenu not take focus/mouse cursor?

    Hello,
    I show() a JPopupMenu based on what the user types in a JTextField, however, when that happens the user typing on the keyboard will no longer write into the text field, unless with the mouse clicks again on the field, thus closing the popup menu.
    I want, like in Eclipse and NetBeans code completion feature, that the user may still type in the field even if the popup menu comes out, although typing might close the popup menu (and in the IDEs that actually generates a new popupmenu with different content).
    How can I achieve that? I thought it had to do with Focus, but it doesn't seem to.

    one way is to have the default invoker/null. However that makes the popup stick, unlike in the ides.

  • Implementing a dynamic Scrollable JPopupMenu

    Hi,
    I wanna make a scrollable JPopupMenu. What I am looking for is I am making a custom popup Menu which extends JPopupMenu. I would be overriding the add method.
    I dont want to add a list or a combo box to my JPopupMenu. I want to change the layout itself .. i.e. there is a function in the Container.class which gets called when we try to add a menuitem dynamically to the JPopupMenu
    Function Name:
    protected void addImpl(Component comp, Object constraints, int index)Snippet which i am looking in the function
    if (layoutMgr instanceof LayoutManager2) {
    ((LayoutManager2)layoutMgr).addLayoutComponent(comp, constraints);
              }Is there a way while addiing menu items dynamically that I can set the layout to scrollable and hence the menuitems when added are in a scrollpane automatically.. Hence I what i get also is a Scrollable JPopupMenu

    well, this is implementation of PopupMenu with scroll
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsConfiguration;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JSeparator;
    public class ScrollPopupMenu extends JPopupMenu {
         private static final long serialVersionUID = 1L;
         private JPanel panelMenus = null;
         private JScrollPane scroll = null;
         public ScrollPopupMenu(GraphicsConfiguration gc) {
              super();
              scroll = new JScrollPane();
              panelMenus = new JPanel();
              panelMenus.setLayout(new GridLayout(0,1));
              scroll.setViewportView(panelMenus);
              scroll.setBorder(null);
              scroll.setMaximumSize(new Dimension(scroll.getMaximumSize().width,
                        this.getToolkit().getScreenSize().height -
                        this.getToolkit().getScreenInsets(gc).top -
                        this.getToolkit().getScreenInsets(gc).bottom - 4));
              super.add(scroll);
         public void show(Component invoker, int x, int y) {
              this.pack();
              panelMenus.validate();
              int maxsize = scroll.getMaximumSize().height;
              int realsize = panelMenus.getPreferredSize().height;
              int sizescroll = 0;
              if (maxsize < realsize) {
                   sizescroll = scroll.getVerticalScrollBar().getPreferredSize().width;
              scroll.setPreferredSize(new Dimension(
                        scroll.getPreferredSize().width + sizescroll,
                        scroll.getPreferredSize().height));
              super.show(invoker, x, y);
         public void add(JButton menuItem) {
              panelMenus.add(menuItem);
         public void addSeparator() {
              panelMenus.add(new JSeparator());
    }It is very basic, but this to help you, If you want to test, you compile this class:
    import javax.swing.SwingUtilities;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    public class FramePopupMenu extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JButton btnPopup = null;
         private JTextField txtNumElem = null;
         private JLabel lblNumElem = null;
         private JButton getBtnPopup() {
              if (btnPopup == null) {
                   btnPopup = new JButton();
                   btnPopup.setText("Ver men� popup");
                   btnPopup.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             ScrollPopupMenu mnu = new ScrollPopupMenu(FramePopupMenu.this.getGraphicsConfiguration());
                             int n = Integer.parseInt(getTxtNumElem().getText());
                             for (int i=0;i<n;i++)
                                  mnu.add(new JButton("Men� " + (i+1)));
                             mnu.show(btnPopup, btnPopup.getWidth(), 0);
              return btnPopup;
         private JTextField getTxtNumElem() {
              if (txtNumElem == null) {
                   txtNumElem = new JTextField();
                   txtNumElem.setColumns(3);
                   txtNumElem.setText("60");
              return txtNumElem;
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        FramePopupMenu thisClass = new FramePopupMenu();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
         public FramePopupMenu() {
              super();
              initialize();
         private void initialize() {
              this.setSize(274, 109);
              this.setContentPane(getJContentPane());
              this.setTitle("Scroll en un men� popup");
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   lblNumElem = new JLabel();
                   lblNumElem.setText("N�mero de elementos del Men�");
                   FlowLayout flowLayout = new FlowLayout();
                   flowLayout.setHgap(8);
                   flowLayout.setVgap(8);
                   jContentPane = new JPanel();
                   jContentPane.setLayout(flowLayout);
                   jContentPane.add(getBtnPopup(), null);
                   jContentPane.add(lblNumElem, null);
                   jContentPane.add(getTxtNumElem(), null);
              return jContentPane;
    }

Maybe you are looking for

  • BOM, Routing and production order

    Hello Guru, we notice something, our material 1256 has maintain four alternative bom as of this date: Alt BOM       MRP4 Prod version  BOM stat       PV lot size  Routing Grp    Route Lot 1                          ACA                            02  

  • Open Order quantity in VA05

    Hi experts, i have a issue in VA05 colum "Confirm quantity" and "Order quantity" not matching to VBB-OMENG and VBBE-VMENG. it should be match? I required Open quantity against sales order. i delivred it partialy. thanks/ anurag

  • File association problems with Win2K server

    Hi, I have a client - 5 Macs in a Win2K network. They're designers and store/work on all their jobs on a Win2K volume. About 2 months ago, problems started happening - files lost their application association (mostly all were turned into Unix exec fi

  • Illegible concersions from PDF to Word

    My pdfs recently converted to docx format in Word for Mac (runing Yosemite)  are in unreadable characters. Does anyone have an idea of how to reproduce these files so they can be cut and pasted? Otherwise this $23 a year is going to be a big waste. T

  • Can somebody help me in getting some good material for Regular Expressions and IP Community list

    can somebody help me in getting some good material for Regular Expressions and IP Community list