JPopupMenu - setSelected (JMenuItem)

Hi
I have a popup menu with a number of menu items which I add to the popupMenu. I call setSelected with one of them (not the first added) and then show. But it is always the first item that is shown as being selected, even though when I call getSelectionModel().getSelectedIndex it returns the index of the item I set to be selected.
I can see that others have had similar problems, but haven't been able to find anyone that could answer them.

Why do you want the menu item selected?
This works, but may not fully answer your question. ***************************************************************************************************
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
public class PopupTest extends JFrame implements ActionListener
public static void main( String[] args )
PopupTest test = new PopupTest();
test.pack();
test.show();
private JPopupMenu popup;
private JMenuItem menuItem1;
private JMenuItem menuItem2;
public PopupTest()
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch( Exception e )
popup = new JPopupMenu();
menuItem1 = new JMenuItem( "Item 1");
menuItem1.setActionCommand( "Item 1");
menuItem1.addActionListener( this );
menuItem2 = new JMenuItem( "Item 2");
menuItem2.setActionCommand( "Item 2");
menuItem2.addActionListener( this );
popup.add( menuItem1 );
popup.add( menuItem2 );
JButton button = new JButton("Button 1");
button.setActionCommand("Button 1");
button.addActionListener( this );
this.getContentPane().add( button );
button = new JButton("Button 2");
button.setActionCommand("Button 2");
button.addActionListener( this );
this.getContentPane().add( button, BorderLayout.EAST );
public void actionPerformed(ActionEvent e)
          System.out.println(e.getActionCommand());
popup.show( this, 0,0 );
if( e.getActionCommand().equals( "Button 1" ) )
popup.setSelected( menuItem1 );
menuItem1.setArmed( true );
menuItem2.setArmed( false );
else if( e.getActionCommand().equals( "Button 2" ) )
popup.setSelected( menuItem2 );
menuItem1.setArmed( false );
menuItem2.setArmed( true );

Similar Messages

  • MouseEvents on JPopupMenu and JMenuItem

    Hi
    I am trying to get the mouse events from JPopupMenu
    and JMenuItem , but nothing happens
    I display the popup once a button is pressed , the popup is displayed but once I click it there is no response
    can some one help
    I am attaching the code
    import javax.swing.*;
    import java.awt.event.*;
    public class Pop extends JFrame implements ActionListener{
         JPopupMenu popup = new JPopupMenu();
         JMenuItem item = new JMenuItem("one");
         JMenuItem item2 = new JMenuItem("two");
         JButton ok = new JButton("ok");
         Pop(){
              H hand = new H();
              popup.add(item);
              popup.add(item2);
              popup.addMouseListener(hand);
              item.addMouseListener(hand);
              item2.addMouseListener(hand);
              ok.addActionListener(this);
              getContentPane().add(ok);
              setSize(300,300);
              show();
         public void actionPerformed(ActionEvent ee){
              popup.show(ok , 5,5);
         public static void main(String[] args){
              new Pop();
         class H extends MouseAdapter{
              public void mouseClicked (MouseEvent e){
                   JOptionPane.showMessageDialog(null,e.toString());
    }

    If you are just trying to get something done when a menuitem is clicked, then you can try to use actionListener instead of the mouselistener. Try the following:
    ActionListener al = new ActionListener()
    public void actionPerformed()
    OptionPane.showMessageDialog(null,e.toString());
    item.addActionListener(al);
    item2.addActionListener(al2);
    Now when you click an item, the dialog box would be shown.

  • JPopupMenu for a JTree, enabling and disabling options

    Hi all.
    I'm trying to activate/deactivate some JMenuItem options for a JPopupMenu launched for a JTree object.
    Let's say, depending on "some state", I want some options in the JPopupMenu (the JMenuItems) should be enabled or disabled, and change whenever that state changes.
    I'm trying to activate this feature with "((JMenuItem) item).setEnabled(true)" but the PopupMenu option is still disabled.
    Can some one help me, please?
    Thanks a lot in advance.
    -- Arturo

    Hi all.
    I'm trying to activate/deactivate some JMenuItem options for a JPopupMenu launched for a JTree object.
    Let's say, depending on "some state", I want some options in the JPopupMenu (the JMenuItems) should be enabled or disabled, and change whenever that state changes.
    I'm trying to activate this feature with "((JMenuItem) item).setEnabled(true)" but the PopupMenu option is still disabled.
    Can some one help me, please?
    Thanks a lot in advance.
    -- Arturo

  • JPopupMenu SelectionManager error!

    The following little test program results in both Exception, and or VM crash!!!!
    import javax.swing.*;
    import java.awt.event.*;
    class Pop{
    JDialog m_dialog;
    JPopupMenu m_menu;
    public static void main(String[] args){
    new Pop();
    public Pop(){
    m_dialog = new JDialog();
    m_dialog.addMouseListener(new RightMouseListener());
    m_dialog.setSize(200,200);
    m_menu = new JPopupMenu("Menu");
    JMenuItem item1 = new JMenuItem("1");
    m_menu.add(item1);
    JMenuItem item2 = new JMenuItem("2");
    m_menu.add(item2);
    JMenu item3 = new JMenu("3");
    m_menu.add(item3);
    JMenuItem item3_1 = new JMenuItem("3.1");
    item3.add(item3_1);
    m_dialog.setVisible(true);
    private class RightMouseListener extends MouseAdapter{
    public void mouseClicked(MouseEvent e){
    if(e.getModifiers()==InputEvent.BUTTON3_MASK){
    m_menu.show(m_dialog, e.getX(), e.getY());
    Brings up a little dialog. Press right mouse button, and a little popup apears.
    Click and hold on the first menu item, drag the mouse FAST out of the popup menu, (it should be deselected) and move the mouse pointer back into the popup menu, all the while holding down the mouse button.
    This should result in a trace:
    java.lang.ArrayIndexOutOfBoundsException: 1073741823
    at javax.swing.MenuSelectionManager.processMouseEvent(MenuSelectionManager.java:238, Compiled Code)
    at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mouseDragged(BasicMenuItemUI.java:924, Compiled Code)
    at java.awt.Component.processMouseMotionEvent(Component.java:3759, Compiled Code)
    at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2377, Compiled Code)
    at java.awt.Component.processEvent(Component.java:3548, Compiled Code)
    at java.awt.Container.processEvent(Container.java:1165, Compiled Code)
    at java.awt.Component.dispatchEventImpl(Component.java:2593, Compiled Code)
    at java.awt.Container.dispatchEventImpl(Container.java:1214, Compiled Code)
    at java.awt.Component.dispatchEvent(Component.java:2497, Compiled Code)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2452, Compiled Code)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2206, Compiled Code)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2126, Compiled Code)
    at java.awt.Container.dispatchEventImpl(Container.java:1201, Compiled Code)
    at java.awt.Window.dispatchEventImpl(Window.java:912, Compiled Code)
    at java.awt.Component.dispatchEvent(Component.java:2497, Compiled Code)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:333, Compiled Code)
    at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:103, Compiled Code)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93, Compiled Code)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:84, Compiled Code)
    Any idea why? Is this a bug in java? or am I doing something wrong?
    Now try the next issue.
    Right click to bring up the popup menu. Move the mouse down to menuitem #3, click and hold on it, and drag the mouse fast to the right, straight past item 3.1 and out of the menu. (menu item 3.1 should not be selected.) Now move the mouse straight left back to menu item #3. Observe the whole VM going down with a big trace, and core dump.
    Again I ask, am I doing something wrong? Or is it a bug?

    Ouch!
    Looks like Sun will have to give you the Dukes on this one. I sugget you file a bug report in Bugs Parade because it sure looks like one...and feels like one. But Sun may shrug it off by saying that menus are not meant to be used the way you're using (or abusing) it!
    V.V.

  • 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!!!

  • Problem with key mnemonics in JPopupMenu

    Hello everyone...
    Since mnemonics do not work in a popup menu using Java sdk 1.3 (due to a bug), i am currently trying to implement this fuctionality myself. However i have a few problems...
    Please consider the following chunk of code:
    textAreaOut = new JTextArea(6, 0)
         protected void processKeyEvent(KeyEvent event)
    if (((event.getKeyChar() == 'T') || (event.getKeyChar() == 't')) &&
                        (textAreaOutPop.isVisible() == true) && (cutItem.isEnabled() == true))
                             if (event.getID() == KeyEvent.KEY_PRESSED)
                                  System.out.println("Cut");
                                  cutItem.doClick();
                                  textAreaOutPop.setVisible(false);
                             else event.consume();
                        else super.processKeyEvent(event);
    What i am trying to do is to get a keyEvent when the popup menu is visible and the menuItem is enabled. I put that in a proccessKeyEvent in order to override the typing of mnemonics inside the JTextArea.
    Unfortunately i am unable to make this to work, as there is a character typed into the textArea after i press the mnemonic (although the mnemonic now works). Since the proccessKeyEvent captures both KEY_PRESSED and KEY_RELEASED i added an extra if statement but that does not seem to solve the problem.
    Could please someone tell me whats wrong with my code sample? is there any better way to implement mnemonics in a JPopupMenu?
    Thanks for your time
    John

    I found a solution myself... Using the following code i make the mnemonics to work on the JPopupMenu in jdk 1.3
    textAreaOut = new JTextArea(6, 0)
                   protected void processKeyEvent(KeyEvent event)
                        if (event.isControlDown() == true)
                        menuBar.requestFocus();
                        else if (firePopupMenuItem('U', 'u', textAreaOutPop, undoItem1, event) == true);
                        else if (firePopupMenuItem('T', 't', textAreaOutPop, cutItem, event) == true);
                        else if (firePopupMenuItem('C', 'c', textAreaOutPop, copyItem1, event) == true);
                        else if (firePopupMenuItem('P', 'p', textAreaOutPop, pasteItem, event) == true);
                        else if (firePopupMenuItem('D', 'd', textAreaOutPop, deleteItem1, event) == true);
                        else if (firePopupMenuItem('A', 'a', textAreaOutPop, selectAllItem1, event) == true);
                        else if (firePopupMenuItem('S', 's', textAreaOutPop, sendItem, event) == true);
                        else if (textAreaOutPop.isVisible() == true)
                        event.consume();
                        else super.processKeyEvent(event);
    and the firePopupMenuItem mehtod...
    private boolean firePopupMenuItem(char mnemonic1, char mnemonic2, JPopupMenu puMenu,
         JMenuItem puMenuItem, KeyEvent ke)
              if (((ke.getKeyChar() == mnemonic1) || (ke.getKeyChar() == mnemonic2)) &&
              (puMenu.isVisible() == true) && (puMenuItem.isEnabled() == true))
                   //Testing
                   System.out.println("firePopupMenuItem");
                   if (ke.getID() == ke.KEY_PRESSED)
                   puMenuItem.doClick();
                   else puMenu.setVisible(false);
                   return true;
              return false;
    However, there is a small problem...
    When i use a mnemonic the event is executed and the JPopupMenu closes (which is fine) however when the popup menu is closed if i click at exactly the same point of where i clicked to open it the mouse event will not trigger and i have to do 2 clicks in order to open again the popup menu again. This is not happening if the mouse click is in different location (i.e. the popup menu opens with only 1 mouse click)...
    Anyone knows why?
    Thanks,
    John

  • An array of JPopupMenu

    Hi Guys,
    Is it possible to create an array of JPopupMenu using an array JMenuItem. If it can be used, is this right: -
    JPopupMenu ar[] = new JPopupMenu[4];
    JMenuItem it[] = new JMenuItem[12];
    How can I put the menu items in to popup menus.
    for instance, if I want it[0] and it[1] to put into ar[0].
    Thanks

    Hi,
    I used "ar[0].add(it[0]);ar[0].add(it[1]); " and I got the following error which I think means, there is no value in the popup menu instance.
    If you can help it would be helpful.
    Thanks
    java.lang.NullPointerException
    at Popup_Menus.<init>(Popup_Menus.java:35)
    at GUICanvas.<init>(GUICanvas.java:15)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    at java.lang.Class.newInstance0(Class.java:306)
    at java.lang.Class.newInstance(Class.java:259)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:567)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:496)
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:536)

  • JpopupMenu not displaying

    hi all,
    why the JPopupMenu is not displaying here?
    is this line not registering mouseListener
    enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    import java.awt.AWTEvent;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class DemoPopUp extends JFrame{
        protected JPopupMenu popupMenu = new JPopupMenu();
        protected JMenuItem m_mniInsertRow;
        protected JMenuItem m_mniInsertScrip;
        protected JMenuItem m_mniDeleterRow;
        protected JMenuItem m_mniDeleteExpiredScrip;
        protected JMenuItem m_mniSetAlert;
        JTable tbl = new JTable(100, 8){
            public Object getValueAt(int row, int col) {
                return row+","+col;
        public DemoPopUp(){
            m_mniInsertRow = new JMenuItem("Insert a Row");
            m_mniInsertScrip = new JMenuItem("Insert a Scrip");
            m_mniDeleterRow = new JMenuItem("Delete a Row");
            m_mniDeleteExpiredScrip = new JMenuItem("Delete a Expired Scrip");
            m_mniSetAlert = new JMenuItem("Set Alert");
            popupMenu.add(m_mniInsertRow);
            popupMenu.add(m_mniInsertScrip);
            popupMenu.add(m_mniDeleterRow);
            popupMenu.add(m_mniDeleteExpiredScrip);
            popupMenu.add(m_mniSetAlert);
            enableEvents(AWTEvent.MOUSE_EVENT_MASK);
            JPanel jp = new JPanel();
            JScrollPane src = new JScrollPane(tbl);
            jp.add(src);
            getContentPane().add(jp);
            setVisible(true);
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public void processMouseEvent( MouseEvent evt )
            if( evt.isPopupTrigger() )
              JTable source = (JTable)evt.getSource();
              int row = source.rowAtPoint( evt.getPoint() );
              int column = source.columnAtPoint( evt.getPoint() );
              System.out.println(column);
              source.changeSelection(row, column, false, false);
              popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
        public static void main(String[] args)
            new DemoPopUp();
    }thanks
    daya

    is this line not registering mouseListener
    enableEvents(AWTEvent.MOUSE_EVENT_MASK);No and you don't need that line.
    For general usage of a MouseListener, read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/events/handling.html]How to Use a Mouse Listener
    For specific information on popups, read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#popup]Bringing Up a Popup Menu for a working example.

  • Chekong a JCheckBox in a JPopupMenu

    I added four JCheckBoxes to my JPopupMenu.
    before popping up I want to Check/ Uncheck these components.
    How can I do this?

    Your right, but there is a setSelected(...) methodas
    mentioned above and it takes a parameter.JPopUpMenu.setSelected ( Component sel);
    sel = the component to set
    Thats what I found. There is no boolean parameter!http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/AbstractButton.html#setSelected(boolean)

  • JPopupMenu Vertical Text

    Hi all, i want to add a text to my popup menu with vertical position at the right side of menu. But i couldnt find any information.
    Do u know how can i handle that? Is there anybody who know it??

    It's a hack. And I couldn't find a L&F that actually displays the popup menu's label, although the API says
    label - the string that a UI may use to display as a title for the popup menu.
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    public class PopupWithVerticalTitle {
       final PopupFactory factory = PopupFactory.getSharedInstance();
       Popup popup;
       JPopupMenu popupMenu;
       JPanel outer, inner;
       JFrame frame;
       int popupWidth;
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new PopupWithVerticalTitle().makeUI();
       public void makeUI() {
          popupMenu = new JPopupMenu("popupmenu1");
          JMenuItem item1 = new JMenuItem("menuItem1");
          popupMenu.add(item1);
          JMenuItem item2 = new JMenuItem("menuItem2");
          popupMenu.add(item2);
          JMenuItem item3 = new JMenuItem("menuItem3");
          popupMenu.add(item3);
          popupMenu.addPopupMenuListener(new PopupMenuListener() {
             public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
             public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                popup.hide();
             public void popupMenuCanceled(PopupMenuEvent e) {
          String title = "TITLE";
          inner = new JPanel(new GridLayout(0, 1));
          for (int i = 0; i < title.length(); i++) {
             JLabel label = new JLabel(title.substring(i, i + 1));
             label.setHorizontalAlignment(JLabel.CENTER);
             inner.add(label);
          outer = new JPanel();
          outer.setBorder(UIManager.getBorder("PopupMenu.border"));
          outer.add(inner);
          Dimension popupSize = popupMenu.getPreferredSize();
          Dimension outerSize = outer.getPreferredSize();
          popupWidth = popupSize.width;
          int height = Math.max(popupSize.height, outerSize.height);
          outer.setPreferredSize(new Dimension(outerSize.width, height));
          popupMenu.setPopupSize(popupWidth, height);
          frame = new JFrame();
          frame.getContentPane().addMouseListener(new MouseAdapter() {
             @Override
             public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                   showPopup(e);
             @Override
             public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                   showPopup(e);
             private void showPopup(MouseEvent e) {
                popup = factory.getPopup(frame.getContentPane(),
                      outer,
                      e.getXOnScreen() + popupWidth - 1,
                      e.getYOnScreen());
                popup.show();
                popupMenu.show((Component) e.getSource(), e.getX(), e.getY());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(300, 300);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    }db

  • About popup hide

    Question F
    1.How dose JPopupMenu or JMenuItem hiden ,when click any where .
    2.How dose JComboBox's dropdown hidden ,when click any where.
    3.Question1,2 is one answer?
    I tried to read JComponent ,Popup ,PopupFactory ,JPopupMenu,JCombox and others source code,but in few day I can't find the way .Please help me and give directions B
    JTextField editing ,dropdown a JPopupMenu contain maybe input words,but focus lost,can't still edit JTextField;
    Edited by: tlw_ray on Oct 22, 2008 11:40 PM

    Thans for you camickr .
    My question is I dosen't know the theory , how swing manage popup item hiden;
    I want a JTextField ,when I input word,it can drop down a popup assistant help me auto complete.
    First I use PopupFactory to implement the function,but finally I notice that I can't hide the popup in an evnent.
    Then I think maybe use somethin like menu can implement the function.So I use JPopupMenu ,but when it popup,the JTextField's focuse lose,I can't input still.then when JPopupMenu shown I set jTextField to requestFocuse().That's all .My problem resolved.But I still dose't know how the JPopupMenu hiden ,when click any where but the menu.And I tried use JWindow ,but it dosen't catch the deActive window event.
    I hope can understand how swing manager popup show or hiden,maybe intro some article or indicate some code block can help me .I like java for he tell me what he do when a program running,
    Utility Class:
    import java.awt.Component;
    import javax.swing.JFrame;
    Author:&#21776;&#21147;&#20255;
    E-Mail:[email protected]
    Date:2008-10-22
    Description:
    public class Shower {
         public static void show(Component comp,int width,int height){
              JFrame f=new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(width, height);
              f.setLocationRelativeTo(null);
              f.add(comp,"Center");
              f.setVisible(true);
         public static void show(Component comp){
              show(comp,400,300);
    }Here is my exmaple code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Window;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JTextField;
    import javax.swing.JWindow;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    import tlw.example.Shower;
    Author:tlw_ray
    E-Mail:[email protected]
    Date:2008-10-23
    Description:input assistant
    public class JTextFieldKindsOfPopup extends JPanel{
         private static final long serialVersionUID = 1L;
         public static void main(String[] args) {
              JTextFieldKindsOfPopup wp=new JTextFieldKindsOfPopup();
              Shower.show(wp);
         JTextField jtfWindowPopuup=new JTextField("Edit for Popup JWindow",20);
         JTextField jtfMenuPopup=new JTextField("Edit for Popup JPopupMenu",20);
         JTextField jtfPopup=new JTextField("Edit for PopupFactory Popup",20);
         Window popupWindow=new JWindow();
         JPopupMenu popupMenu=new JPopupMenu();
         Popup popup;
         JPanel popupPane=new JPanel();
         public JTextFieldKindsOfPopup(){
              add(jtfWindowPopuup,"North");
              add(jtfMenuPopup,"South");
              add(jtfPopup,"Center");
              //popup window
              popupWindow.setPreferredSize(new Dimension(300,300));
              popupWindow.setBackground(Color.red);
              popupWindow.setBounds(20, 20, 100, 100);
              popupWindow.setAlwaysOnTop(true);
              popupWindow.addWindowListener(new WindowListener());
              jtfWindowPopuup.addKeyListener(new KeyAdapter(){
                   public void keyPressed(KeyEvent e){
                        popupWindow.setVisible(true);
                        //JWindow dosen't catch windowDeactivated event;
              //popup menu
              JMenuItem menuItem1=new JMenuItem("Item1");
              JMenuItem menuItem2=new JMenuItem("Item2");
              JMenuItem menuItem3=new JMenuItem("Item3");
              popupMenu.add(menuItem1);
              popupMenu.add(menuItem2);
              popupMenu.add(menuItem3);
              jtfMenuPopup.addKeyListener(new KeyAdapter(){
                   public void keyPressed(KeyEvent e){
                        popupMenu.show(jtfMenuPopup, 0, jtfMenuPopup.getHeight());
                        jtfMenuPopup.requestFocus();
                        //this way can resolve,input assistant
              //popup factory
              popupPane.setBackground(Color.blue);
              popupPane.setPreferredSize(new Dimension(100,100));
              jtfPopup.addKeyListener(new KeyAdapter(){
                   public void keyPressed(KeyEvent e){
                        popup=PopupFactory.getSharedInstance().getPopup(JTextFieldKindsOfPopup.this, popupPane, 100, 100);
                        popup.show();
                        //what event can i set the popup hide()?
                        //maybe popupFactory dosen't use for this ,it just use to Tooltip.
         class WindowListener extends WindowAdapter{
              @Override
              public void windowDeactivated(WindowEvent e) {
                   popupWindow.setVisible(false);
    }Here is my function code
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.text.Collator;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Locale;
    import java.util.Vector;
    import javax.swing.JCheckBox;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    Author:tlw
    E-Mail:[email protected]
    Date:2008-10-23
    Description:
    public class MSearch1 extends JPanel {
         private static final long serialVersionUID = 1L;
         public static void main(String[] args) {
              final MSearch1 ms=new MSearch1();
              ms.setItems(new String[]{"aaa","aab","aac","W3.UNIT1.E0003","W3.UNIT1.E0004","W3.UNIT1.E0005"});
              final JCheckBox jckDropDownMode=new JCheckBox("isDropDownMode");
              jckDropDownMode.setSelected(ms.getIsDropDown());
              jckDropDownMode.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        ms.setIsDropDownModel(jckDropDownMode.isSelected());
              final JCheckBox jckFilterMode=new JCheckBox("isFilterMode");
              jckFilterMode.setSelected(ms.getIsFilterMode());
              jckFilterMode.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        ms.setIsFilter(jckFilterMode.isSelected());
              final SpinnerNumberModel jspinModel=new SpinnerNumberModel(8,3,15,1);
              final JSpinner jspinnerRows=new JSpinner(jspinModel);
              jspinnerRows.setToolTipText("drop down item count.");
              jspinnerRows.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        int rowCount=jspinModel.getNumber().intValue();
                        ms.setRows(rowCount);
              JPanel paneLeft=new JPanel();
              paneLeft.setLayout(new GridLayout(3,1));
              paneLeft.add(jckDropDownMode);
              paneLeft.add(jckFilterMode);
              paneLeft.add(jspinnerRows);
              JPanel pane=new JPanel();
              pane.setLayout(new BorderLayout());
              pane.add(ms,"Center");
              pane.add(paneLeft,"West");
              Shower.show(pane);
         /*---------user interface element-----------*/
         private JTextField jtfInput=new JTextField();
         private JList jlistReservior=new JList();
         private JScrollPane jscroll4List=new JScrollPane(jlistReservior);
         private JPopupMenu jpopup4List=new JPopupMenu();
         /*---------self property--------------*/
         private boolean isDropDownMode=true;
         private boolean isFilterMode=true;
         private int rows=8;
         private String[] items;
         /*---------constructor--------------*/
         public MSearch1(){
              initUI();
              initEvent();
         private void initUI(){
              jtfInput.setColumns(20);
              //Dimension listSize=new Dimension(20*16,rows*25);
              //jscroll4List.setPreferredSize(listSize);
              setLayout(new BorderLayout());
              add(jtfInput,"North");
              dropModelRefresh();
         private void initEvent(){
              jtfInput.getDocument().addDocumentListener(inputChange);
              jtfInput.addKeyListener(inputKeyListener);
              jtfInput.addComponentListener(resizeListener);
              jlistReservior.addMouseMotionListener(mouseOverShow);
              jlistReservior.addMouseListener(clickSelect);
         //filter items who start with user input;
         private void doFilter(){
              String txt=jtfInput.getText().toLowerCase();
              if(isFilterMode){
                   if(items==null){
                        throw new RuntimeException("please use setItems() to initialize items for select¡£");
                   List fileteredList=new Vector();//<String>
                   for(int i=0;i<items.length;i++){
                        if(items.toLowerCase().startsWith(txt)){
                             fileteredList.add(items[i]);
                   jlistReservior.setListData(fileteredList.toArray());
                   jlistReservior.setSelectedIndex(0);
              }else{
                   jlistReservior.setSelectedIndex(-1);
                   for(int i=0;i<items.length;i++){
                        if(items[i].toLowerCase().startsWith(txt)){
                             jlistReservior.setSelectedValue(items[i], true);
                             return;
         private void refreshPopup(){
              if(isDropDownMode){
                   if(jpopup4List==null){
                        jpopup4List=new JPopupMenu();
                        jpopup4List.add(jscroll4List);
                   jpopup4List.show(jtfInput, jtfInput.getX(), jtfInput.getY()+jtfInput.getHeight());
                   jtfInput.requestFocus();
         //listening user jtfInput change;
         private DocumentListener inputChange=new InputChange();
         class InputChange implements DocumentListener{
              public void changedUpdate(DocumentEvent e) {inputChanged();}
              public void insertUpdate(DocumentEvent e) {inputChanged();}
              public void removeUpdate(DocumentEvent e) {inputChanged();}
              private void inputChanged(){
                   doFilter();
                   refreshPopup();
         //listening user mouse double click jtfInput
         private DoubleClickDropDown clickDropDown=new DoubleClickDropDown();
         class DoubleClickDropDown extends MouseAdapter{
              public void mouseClicked(MouseEvent e){
                   if(e.getButton()==MouseEvent.BUTTON1
                             && e.getClickCount()==2){
                        refreshPopup();
         //listening user click drop down list menu ,select item;
         private ClickSelect clickSelect=new ClickSelect();
         class ClickSelect extends MouseAdapter{
              public void mouseClicked(MouseEvent e){
                   selectInDropDown();
         private void selectInDropDown(){
              jtfInput.setText(jlistReservior.getSelectedValue().toString());
              jpopup4List.setVisible(false);
         //listening user control key;
         private KeyListener inputKeyListener=new InputKeyListener();
         class InputKeyListener extends KeyAdapter{
              public void keyPressed(KeyEvent e){
                   int selected=jlistReservior.getSelectedIndex();
                   if(e.getKeyCode()==KeyEvent.VK_UP){
                        if(selected>0){
                             jlistReservior.setSelectedIndex(selected-1);
                   }else if(e.getKeyCode()==KeyEvent.VK_DOWN){
                        if(selected<(jlistReservior.getModel().getSize()-1)){
                             jlistReservior.setSelectedIndex(selected+1);
                   }else if(e.getKeyCode()==KeyEvent.VK_ENTER){
                        selectInDropDown();
         //listening list mouse over select
         private MouseMotionAdapter mouseOverShow=new MouseOverSelect();
         class MouseOverSelect extends MouseMotionAdapter{
              public void mouseMoved(MouseEvent e){
                   int selected=jlistReservior.getSelectedIndex();
                   int current=jlistReservior.locationToIndex(e.getPoint());
                   if(selected!=current)
                        jlistReservior.setSelectedIndex(current);
         //listening when jtfInput resize
         private ComponentListener resizeListener=new ResizeListener();
         class ResizeListener extends ComponentAdapter{
              public void componentResized(ComponentEvent e){
                   refreshSize();
         /*--------------weather drop down mode---------------------*/
         public boolean getIsDropDown(){
              return isDropDownMode;
         * É趨ÏÂÀģʽ£¬»ò¹Ì¶¨Ä£Ê½¡£É趨ºó×Ô¶¯Ë¢Ð½çÃæ¡£
         * @param dropDown true ±íʾÏÂÀģʽ£¬false ±íʾ¹Ì¶¨Ä£Ê½
         public void setIsDropDownModel(boolean dropDown){
              isDropDownMode=dropDown;
              dropModelRefresh();
              validate();
              repaint();
         private void dropModelRefresh(){
              if(isDropDownMode){
                   remove(jscroll4List);
                   jpopup4List.add(jscroll4List);
                   jtfInput.addMouseListener(clickDropDown);
              }else{
                   jpopup4List.remove(jscroll4List);
                   add(jscroll4List,"Center");
                   jtfInput.removeMouseListener(clickDropDown);
         /*--------------------drop down items-------------------------*/
         public void setItems(String[] strs){
              items=strs;
              refreshItems();
         public String[] getItems(){
              return items;
         private void refreshItems(){
              //if is filter mode ,items may be ordered;
              Comparator cmp = Collator.getInstance(Locale.getDefault());
              java.util.Arrays.sort(items, cmp);
              jlistReservior.setListData(items);
         /*---------------------weather filter mode------------------------*/
         public void setIsFilter(boolean isFilter){
              isFilterMode=isFilter;
              refreshItems();
         public boolean getIsFilterMode(){
              return isFilterMode;
         /*---------------------size property---------------------------------*/
         public int getRows(){
              return rows;
         public void setRows(int rowCount){
              rows=rowCount;
              refreshSize();
              validate();
              repaint();
         public int getColumns(){
              return jtfInput.getColumns();
         public void setColumns(int colCount){
              jtfInput.setColumns(colCount);
              validate();
              repaint();
         private void refreshSize(){
              Font font=jlistReservior.getFont();
              FontMetrics fm=jlistReservior.getFontMetrics(font);
              int height=fm.getHeight()*rows;
              //int height=jlistReservior.getFixedCellHeight()*rows;
              System.out.println(jlistReservior.getFixedCellHeight());
              Dimension size=new Dimension(jtfInput.getWidth(), height);
              jscroll4List.setPreferredSize(size);
         /*--------------------input text property-------------------*/
         public String getText(){
              return jtfInput.getText();
         public void setText(String text){
              jtfInput.setText(text);
    Edited by: tlw_ray on Oct 23, 2008 10:56 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

  • Error about getAppletContext() method

    I want to control my popup menus and thier actions in class called Popup_Menus then create an instance of this class in an other class which allows me to use the popup menus.
    When I compile Popup_Menus class I am getting the following error: -
    Popup_Menus.java [79:1] cannot resolve symbol
    symbol: method getAppletContext ()
    getAppletContext().showDocument(url,s);
    ^
    1 error
    Errors compiling Popup_Menus.
    Here is the code in my Popup_Menus class: -
    public class Popup_Menus {
    JPopupMenu ar[] = new JPopupMenu[16];
    JMenuItem it[] = new JMenuItem[84];
    public Popup_Menus() {
    for (int i=0;i<16;i++)
    ar[i] = new JPopupMenu();
    for (int i=0;i<84;i++)
    it[i] = new JMenuItem();
    it.setBackground(Color.orange);
    it[i].setForeground(Color.cyan);
    it[16]= new JMenuItem("abdi");
    it[17]= new JMenuItem("ganni");
    it[18]= new JMenuItem("magan");
    it[0] = new JMenuItem("Oracle");
    ar[0].add(it[0]);
    it[1] = new JMenuItem("Macrosoft");
    ar[1].add(it[1]);
    it[2] = new JMenuItem("SunMicro");
    ar[2].add(it[2]);
    it[3] = new JMenuItem("PeopleSoft");
    ar[3].add(it[3]);
    it[4] = new JMenuItem("HP");
    ar[4].add(it[4]);
    it[5] = new JMenuItem("Dell");
    ar[5].add(it[5]);
    it[6] = new JMenuItem("Compact");
    ar[6].add(it[6]);
    it[7] = new JMenuItem("Apple");
    ar[7].add(it[7]);
    it[8] = new JMenuItem("Sony");
    ar[8].add(it[8]);
    it[9] = new JMenuItem("Philipes");
    ar[9].add(it[9]);
    it[10] = new JMenuItem("Bush");
    ar[10].add(it[0]);
    it[11] = new JMenuItem("Granada");
    ar[11].add(it[11]);
    it[12] = new JMenuItem("PC");
    ar[12].add(it[12]);
    it[13] = new JMenuItem("Macintosh");
    ar[13].add(it[13]);
    it[14] = new JMenuItem("Laptop");
    ar[14].add(it[14]);
    it[15] = new JMenuItem("Solaris");
    ar[15].add(it[15]);
    it[0].addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    System.out.println("Working");
    try
    String s="ali";
    URL url = new URL("http://www.google.com");
    getAppletContext().showDocument(url,s);
    catch(MalformedURLException malformedurlexception)
    System.err.println(malformedurlexception);
    Thanks for your help guys.

    Thanks Sandeep. I replace the count with RCOUNT and i'm not getting the error. Can you tell me what did this do by adding Rcount to my formula? Also i'm still getting the error with my actual execution rate. THis is a different formula. The actual execution rate is below:
    SUM( CASE WHEN MQCREPORT.HPQC_TEST_SET.TC_EXEC_STATUS = 'Passed' OR MQCREPORT.HPQC_TEST_SET.TC_EXEC_STATUS = 'Failed' THEN 1 ELSE 0 END ) / ( TIMESTAMPDIFF( SQL_TSI_DAY , TIMESTAMPADD( SQL_TSI_DAY , 7 - DAYOFWEEK(MQCREPORT.HPQC_REL_CYCL.REL_START_DATE), MQCREPORT.HPQC_REL_CYCL.REL_START_DATE), TIMESTAMPADD( SQL_TSI_DAY , 7 - DAYOFWEEK( CURRENT_DATE ), CURRENT_DATE )) / 7 * 5 + CASE 7 - DAYOFWEEK(MQCREPORT.HPQC_REL_CYCL.REL_START_DATE) WHEN 6 THEN 5 ELSE 7 - DAYOFWEEK(MQCREPORT.HPQC_REL_CYCL.REL_START_DATE) END - CASE 7 - DAYOFWEEK( CURRENT_DATE ) WHEN 6 THEN 5 ELSE 7 - DAYOFWEEK( CURRENT_DATE ) END ) * 1.0

  • Double click event to source code

    hi all
    What im trying to do is when someone clicks one of the keywords in the tree browser file that it takes them to the source code window and to that method or variable the clicked. For exaple lets say have 2 windows, on the left side is just a list of methods and variables and ont he right hand is the window which u can see the source code. What i need is that when someone click on a method name on the left window, it will take them directly to that method name in the source file window (right window).
    public void mouseClicked(MouseEvent e)
    Any ideas what i need to do??
    Maybe it will help if i copy and paste the code of the [b]left window.
    import java.util.Observable;
    import antlr.collections.AST;
    import java.awt.Font;
    import java.awt.event.*;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.border.TitledBorder;
    public class FileContentPanel extends ModulePanel {
        private ProgramModel model;
        private JTree contentTree;
        private APIViewer api;
        private SourceViewWindow view;
        private Formatter format;
        private FileTree tree;
        private JPopupMenu menu = new JPopupMenu();
        private JMenuItem viewmenu;
        /** Creates a new instance of FileContentWindow */
        public FileContentPanel(ProgramModel model, APIViewer a) {
            super(model, "File Contents");
            this.api = a;
            createPopupMenu();
            contentTree = new JTree() {
                public String getToolTipText(MouseEvent evt, ActionListener l) {
                    if (getRowForLocation(evt.getX(), evt.getY()) == -1)
                        return null;
                    TreePath curPath = getPathForLocation(evt.getX(), evt.getY());
                    DefaultMutableTreeNode highlighted = (DefaultMutableTreeNode)curPath.getLastPathComponent();
                    Object userOb = highlighted.getUserObject();
                    String ret=highlighted.getUserObject().toString();
                    if (userOb.getClass()==JavaMember.class)
                        ret=((JavaMember)userOb).getSignature();
                    else if (userOb.getClass()==JavaClass.class)
                        ret=((JavaClass)userOb).getSignature();
                    return ret;
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            ImageIcon file = new ImageIcon(Prototype.class.getResource("images/source.gif"));
            renderer.setLeafIcon(file);
            contentTree.addMouseListener(new PopupTrigger());
            contentTree.setCellRenderer(renderer);
            contentTree.setToolTipText("");
            contentTree.setFont(new Font("Arial", Font.PLAIN, 11));
        private void setTree(JavaFile f) {
            ((DefaultTreeModel)contentTree.getModel()).setRoot(f.buildTree());
            getScroller().getViewport().add(contentTree);
        public void update(Observable o, Object arg) {
            setTree((JavaFile)arg);
        public boolean canViewAPI(DefaultMutableTreeNode node) {
            return (!node.isRoot() && node.getParent().toString().equals("imports"));
        private void createPopupMenu() {
            Action viewAPI = new AbstractAction("View API") {
                public void actionPerformed(ActionEvent e) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode)contentTree.getSelectionPath().getLastPathComponent();
                    if (node != null)
                        api.viewAPI(node.toString());
            viewmenu = menu.add(viewAPI);
        class PopupTrigger extends MouseAdapter {
            public void mouseReleased(MouseEvent e) {
                maybeShowPopup(e);
            public void mousePressed(MouseEvent e) {
                maybeShowPopup(e);
                //tree.getTree();
               // System.out.println("U are nearly there");
             public void mouseClicked(MouseEvent e)
               System.out.println("jknxncnnxzv");
            private void maybeShowPopup(MouseEvent e) {
                if (e.isPopupTrigger() ) {
                    int x = e.getX();
                    int y = e.getY();
                    TreePath path = contentTree.getPathForLocation(x, y);
                    if (path == null)
                        return;
                    contentTree.setSelectionPath(path);
                    contentTree.scrollPathToVisible(path);
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
                    if (node != null) {
                        viewmenu.setEnabled(canViewAPI(node));
                    menu.show(contentTree, x, y);
    Cheers

    Does JavaClass contain the list of JavaMembers? If so, and if it is supposed to reflect the current state of the file that is open on the right hand side, then it should probably have methods to get the line and column number for the start of the contained JavaMembers. If you can figure out how to keep that in sync, you should be able to query it directly and set the cursor position.

  • Removing focus from a node

    I have a frame in which a scrollpane hold a jtree.
    I picked up the following code from the forum for making sure that only when the right click is on a node, the popupmenu is displayed.
    public void mouseReleased(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    TreePath closestTreePath = tree.getClosestPathForLocation(e.getPoint(), e.getPoint());
                    if (closestTreePath != null) {
                        tree.setSelectionPath(closestTreePath);
                         // select the row in the tree for the path
                        selectedRow = tree.getRowForPath(closestTreePath);
                        YourNode node = (YourNode) closestTreePath.getLastPathComponent();
                       // assuming your popup menu is already created somewhere else
                       popupMenu.show(deviceTree, pt.x, pt.y);
                        selectedRow = -1;
    }by codecraig
    But now the problem is that whenever i do right click anywhere on the tree a node gets selected and the popupmenu is displyed. i want to display the right click is on the node.
    here is my code
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.event.*;
    public class tree_right_click
         //JPopupMenu popupmenu = new JPopupMenu();
         JTree mytree;
         SysPopupListener s = new SysPopupListener();
         public tree_right_click()
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
              DefaultMutableTreeNode l1 = new DefaultMutableTreeNode("level1");
              DefaultMutableTreeNode l2 = new DefaultMutableTreeNode("level2");
              mytree=new JTree(root);
              mytree.addMouseListener(s);
              root.add(l1);
              l1.add(l2);
              JScrollPane treeview = new JScrollPane(mytree);
              JFrame fr = new JFrame("My Frame");
              fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              fr.getContentPane().add(treeview);
              fr.setSize(300,300);
              fr.setVisible(true);
              public static void main(String args[])
              new tree_right_click();
    class SysPopupListener extends MouseAdapter
         JPopupMenu popupmenu = new JPopupMenu();
         SysPopupListener()
              JMenuItem part = new JMenuItem("Add detail 1");
              JMenuItem part2 = new JMenuItem("Add detail 2");
              part.addMouseListener(this);
              part2.addMouseListener(this);
              popupmenu.add(part);
              popupmenu.add(part2);
         public void mousePressed(MouseEvent e)
              maybeshowpopup(e);
         public void mouseReleased(MouseEvent e)
              maybeshowpopup(e);
         void maybeshowpopup(MouseEvent e)
              if(e.isPopupTrigger())
                   JTree t = (JTree)e.getComponent();
                   TreePath closestTreePath = t.getClosestPathForLocation(e.getX(), e.getY());
                if (closestTreePath != null) {
                    t.setSelectionPath(closestTreePath);
                     // select the row in the tree for the path
                    int selectedRow = t.getRowForPath(closestTreePath);
                    DefaultMutableTreeNode n = (DefaultMutableTreeNode) closestTreePath.getLastPathComponent();
                    System.out.print(n);
                   // assuming your popup menu is already created somewhere else
                    popupmenu.show(e.getComponent(),e.getX(),e.getY());
                    selectedRow = -1;
    }Please help,
    thanks in advance,
    Puneet

    I made some changes to your code and seems to be working like this:
              if(e.isPopupTrigger()) {
                   JTree t = (JTree)e.getComponent();
                   TreePath closestTreePath = t.getClosestPathForLocation(e.getX(), e.getY());
                   if (closestTreePath != null) {
                        t.setSelectionPath(closestTreePath);
                        // select the row in the tree for the path
                        int selectedRow = t.getRowForPath(closestTreePath);
                        DefaultMutableTreeNode n = (DefaultMutableTreeNode) closestTreePath.getLastPathComponent();
                        System.out.print(n);
                        // assuming your popup menu is already created somewhere else
                        popupmenu.show(e.getComponent(),e.getX(),e.getY());
                        selectedRow = -1;
                   JTree t = (JTree)e.getComponent();
                   TreePath path = t.getPathForLocation(e.getX(), e.getY());
                   if (path != null) {
                        popupmenu.show(e.getComponent(),e.getX(),e.getY());
              }

  • Pressed button color

    Hi,
    I have a JPopUpMenu containing JMenuItems. When it is pressed, I would like the JMenuItem to freeze for some time and change color. I freeze it with a simple Thread.sleep(time). My problem is to change the color.
    If I try to change the display in the actionPerformed, the HMI is not updated before the end of the actionPerformed, so the menu disappears.
    I tried to use the UIManager with "menuPressedItemB" and "menuPressedItemF" that I found here:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=183858
    But it looks effectless...
    Any help is welcome. Thx for your attention,
    lolo

    Swing related questions should be posted in the Swing forum. Try setting the following properties on the button:
    setContentAreaFilled( false );
    setOpaque(true);

Maybe you are looking for

  • How can I print a PLD report by code?

    Hi people! How could I print a PLD report by code? or Is that possible to fill a PLD and print it? For example: I want to print a invoice automatically by code. I did it clicking the printer button by code, but that's not the best way, because the pr

  • Multiple instance of same mac on network

    Hello, Running OS X Yosemite, I've noticed multiple instances of the same mac appearing on my home network.  Has anyone else encountered this and know of a way to fix it?  Currently, I have to try more than one instance before I find the "correct" ic

  • I have purchased the Adobe Creative Suite 6 Design & Web Premium but will not allow me to register?

    I have purchased the Adobe Creative Suite 6 Design & web Premium & it will not allow me to register the software --- I'm having to use the trial version --- will you please help me in updating --- the products that I have paid lots of money for? And

  • New laptop, existing iPad and snyc issues

    Ok.  New laptop installed. iTunes installed.  All apps transferred. iTunes music and other sourced music available in iTunes. All my PDF files in iTunes And yes the new iTunes is authorised on my Apple ID. But...      I need to sync my PDFs and I get

  • Contact Picture Not Syncing Correctly

    Hi, I've got an app that gets all my friends pictures from facebook & adds them to my contacts on my iPhone & iPad. The problem is when they are uploaded to iCloud & sent to my contacts on my Mac, the pictures are either blurred or cut in half, see p