TrayIcon with PopupMenu or JPopupMenu ?

Hi. (Sorry for my english.)
I spent last 10 whole days digging menu things in TrayIcon with no success :((.
I have three questions.
I can make JPopupWindow above MS-Windows task bar ( SwingUtilities.windowForComponent( JPupupMenu ).window.setAlwaysOnTop( true ) ) , but how to get keyboard focus/input ????
Looking back to normal PopupMenu ... when it pop up -> it blocks Event Dispatch Thread (EDT) (even if I fire it manually .show() from new Thread , I also tryed install new EventQueue ).
How to make non-blocking PopupMenu ? How to pop up via .show() without "origin" ? ( MouseEvent of TrayIcon returns null in .getComponent() ).
I am using Java 6.0 b105 and u1 b03 at WinXP.
Does anybody know solutions ?
Thanks !
PS: I wrote a very simple example.
It changes tray icon and JPanel background every 0.5 second. The question is : is program continue to work when you popup tray icon menu (right click) ?
This is the last event that goes thru EventQueue after I right click tray icon, and before menu shows (and blocks everythig): java.awt.event.InvocationEvent[INVOCATION_DEFAULT,runnable=sun.awt.windows.WTrayIconPeer$1@128e20a,notifier=null,catchExceptions=false,when=1172501444578] on sun.awt.windows.WToolkit@1e0cf70
//====================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class IsTrayIconMenuBlocking3
     public static void main( String[] args ) throws Exception
          // --- JFrame & JPanel section
          final JPanel jp = new JPanel();
          JFrame jf = new JFrame();
          jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          jf.add( jp );
          jf.setSize( 300 , 300 );
          jf.setVisible( true );
          // --- menu item action
          ActionListener itemExitAction = new ActionListener()
               public void actionPerformed( ActionEvent e )
                    System.out.println( "item action: exit" );
                    System.exit( 0 );
          // --- popup menu
          PopupMenu pm = new PopupMenu( "Tray Menu" );
          MenuItem mi = new MenuItem( "Exit" );
          mi.addActionListener( itemExitAction);
          pm.add( mi );
          // --- system tray & tray icon
          final TrayIcon ti = new TrayIcon( ((ImageIcon)UIManager.getIcon("OptionPane.questionIcon")).getImage() , "Tray Icon" , pm );
          SystemTray st = SystemTray.getSystemTray();
          ti.setImageAutoSize( true );
          st.add( ti );          
          // --- color & icon changing loop
          final Image[] trayIcons = new Image[3];
          trayIcons[0] = ((ImageIcon)UIManager.getIcon("OptionPane.errorIcon")).getImage();
          trayIcons[1] = ((ImageIcon)UIManager.getIcon("OptionPane.warningIcon")).getImage();
          trayIcons[2] = ((ImageIcon)UIManager.getIcon("OptionPane.informationIcon")).getImage();
          Runnable colorChanger = new Runnable()
               private int counter = 0;
               private int icon_no = 0;
               public void run()
                    System.out.println( "Hello from EDT " + counter++ );
                    if( jp.getBackground() == Color.RED )
                         jp.setBackground( Color.BLUE );
                    else
                         jp.setBackground( Color.RED );
                    ti.setImage( trayIcons[icon_no++] );
                    if( icon_no == trayIcons.length ) icon_no = 0;                    
          while( true )
               javax.swing.SwingUtilities.invokeLater( colorChanger);
               try{Thread.sleep( 500 );} catch ( Exception e ){}
//====================================

Hi,
thanks for help.
I am closing this subject.
My solution can be found at http://forums.java.net/jive/thread.jspa?threadID=23466&tstart=0 .
( java.net Forums � Java Desktop Technologies � Swing & AWT � TrayIcon PopupMenu or JPopupMenu ? )
Bye !

Similar Messages

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

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

  • Help with popupmenu

    I have this class declaration as follows:
    class DisplayMouseListener extends MouseAdapter implements MouseListener, MouseMotionListener {
    in my mouseclicked event i have the following code
    public void mouseClicked(MouseEvent evt) {
    Point point = evt.getPoint();
    int ObjectSymbol = globals.getInstance().getState();
    // Do not take any action because the mousePressed event will handle the popupmenu
    if (evt.getButton()== MouseEvent.BUTTON3) {
    return;
    This used to compile and run nicely when i compiled with IntelliJ. but after i explored eclipse. something went wrong. now it compiles, but errors out. I tried normal compilation as well. but no luck. the error i get is
    Exception occurred during event dispatching:
    java.lang.NoSuchMethodError
    Any ideas?

    PopupMenu.show() actually blocks on Windows, though not on Solaris and possibly other unixes.
    So if you only care about Windows, just do whatever you want right after show().
    See this bug: http://developer.java.sun.com/developer/bugParade/bugs/4049083.html
    The latest evaluation indicates that it would be make blocking on Solaris too, but with the glacial pace with which they fix AWT bugs, I wouldn't count on that to happen any time soon.

  • Problem with popupmenu

    I wanted to make a Menu and a PopupMenu and add them the same MenuItems. Wenn I first add them to the Menu and then to the PopupMenu they are only visible in the PopupMenu.
    I don't want to make two MenuItems, so what I can do to use one MenuItem for both?

    All 'Components' (this includes almost everything in awt and swing) have a 'parent'. When you add a Component to a Container, that components parent is set to the container. When you add the same component to another container, the components parent is set to the other container.

  • Memory Leak with JPopupMenu

    It seems there is a memory leak with JPopupMenu. The following program demonstrates this leak. If you run the program, click on show form, and then close the form, the used memory will be GCd appropriately. If you click on show form, then right click on the table to show the popup (even if you dont do anything else with the popup) then close the form, it never GCs the form. I've tried all kinds of crazy things, but I cant seem to find what is keeping the memory from being GCd.
    Peter
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeListener;
    import java.text.DecimalFormat;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.AbstractTableModel;
    @SuppressWarnings("serial")
    public class TriState extends JPanel {
         private static final long               K               = 1024;
         private static final long               M               = K * K;
         private static final long               G               = M * K;
         private static final long               T               = G * K;
         protected static int ctr = 1;
         private JButton                              btnShow          = new JButton("Show Form");
         private JLabel                              lblMem          = new JLabel();
         private static final DecimalFormat     df               = new DecimalFormat("#,##0.#");
         protected Timer                              updateTimer     = new Timer();
         public TriState() {
              this.setLayout(new GridLayout());
              add(btnShow);
              add(lblMem);
              updateTimer.scheduleAtFixedRate(new UpdateTimerTask(), 1000, 1000);
              btnShow.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        FrmReferrals fr = new FrmReferrals();
                        fr.setVisible(true);
         class UpdateTimerTask extends TimerTask {
              public void run() {
                   SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                             dumpMemoryUsage();
         protected void dumpMemoryUsage() {
              System.gc();
              Long t = Runtime.getRuntime().totalMemory();
              long f = Runtime.getRuntime().freeMemory();
              String st = convertToStringRepresentation(t);
              String sf = convertToStringRepresentation(f);
              String su = convertToStringRepresentation(t - f);
              System.out.println("Total:" + st + "(" + t + ") Free:" + sf + "(" + f + ") Used:" + su + "(" + (t - f) + ")");
              lblMem.setText(su + "/" + st);
         public static String convertToStringRepresentation(final long value) {
              final long[] dividers = new long[]{T, G, M, K, 1};
              final String[] units = new String[]{"TB", "GB", "MB", "KB", "B"};
              if (value < 1)
                   throw new IllegalArgumentException("Invalid file size: " + value);
              String result = null;
              for (int i = 0; i < dividers.length; i++) {
                   final long divider = dividers;
                   if (value >= divider) {
                        final double dr = divider > 1 ? (double) value / (double) divider : (double) value;
                        result = df.format(dr) + units[i];
                        break;
              return result;
         private static void createAndShowGUI() {
              JFrame frame = new JFrame("SimpleTableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TriState newContentPane = new TriState();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         protected class PopupMenu extends JPopupMenu {
              public PopupMenu() {
                   JRadioButtonMenuItem item1 = new JRadioButtonMenuItem(new AbstractAction("Insert Item") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                             System.out.println(e.getActionCommand());
                   item1.setActionCommand("Insert");
                   add(item1);
                   JRadioButtonMenuItem item2 = new JRadioButtonMenuItem(new AbstractAction("Delete Item") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                             System.out.println(e.getActionCommand());
                   item2.setActionCommand("Delete");
                   add(item2);
         public class FrmReferrals extends JFrame {
              public FrmReferrals() {
                   super();
                   init();
              protected void init() {
                   jbInit();
              protected void closeIt() {
                   uninit();
              // variables here
              protected Dimension          dimPreferred     = new Dimension(1270, 995);
              protected JTabbedPane     tabbedPane          = new JTabbedPane();
              protected JTable          tblReferrals     = null;
              protected PopupMenu          popMenu           = new PopupMenu();
              protected void jbInit() {
                   setPreferredSize(dimPreferred);
                   setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   setTitle("Referrals");
                   JPanel pnl = new JPanel();
                   pnl.setOpaque(false);
                   pnl.setLayout(new BorderLayout());
                   pnl.add(tabbedPane, BorderLayout.CENTER);
                   // put it all in the frame
                   add(pnl);
                   pack();
                   setLocationRelativeTo(null);
                   // init the table and model
                   ReferralsTableModel ctm = new ReferralsTableModel(buildDummyVector());
                   tblReferrals = new JTable(ctm);
                   tblReferrals.setComponentPopupMenu(popMenu);
                   tblReferrals.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                   tabbedPane.add(new JScrollPane(tblReferrals, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
                   addWindowListener(new WindowListener() {
                        @Override
                        public void windowActivated(WindowEvent e) {}
                        @Override
                        public void windowClosed(WindowEvent e) {}
                        @Override
                        public void windowClosing(WindowEvent e) {
                             closeIt();
                        @Override
                        public void windowDeactivated(WindowEvent e) {}
                        @Override
                        public void windowDeiconified(WindowEvent e) {}
                        @Override
                        public void windowIconified(WindowEvent e) {}
                        @Override
                        public void windowOpened(WindowEvent e) {}
              protected Vector<DBO_Referrals> buildDummyVector() {
                   Vector<DBO_Referrals> vr = new Vector<DBO_Referrals>();
                   for (int x = 0; x < 5000; x++) {
                        DBO_Referrals r = new DBO_Referrals(x+(5000*ctr));
                        vr.add(r);
                   return vr;
              protected void uninit() {
                   tblReferrals.setComponentPopupMenu(null);
                   for (Component c : popMenu.getComponents()) {
                        PropertyChangeListener[] pl = c.getPropertyChangeListeners();
                        for (PropertyChangeListener l : pl)
                             c.removePropertyChangeListener(l);
                        if (c instanceof JMenuItem) {
                             ActionListener [] al = ((JMenuItem)c).getActionListeners();
                             for (ActionListener l : al) {
                                  ((JMenuItem)c).removeActionListener(l);
                   popMenu = null;
              protected class DBO_Referrals {
                   protected long          id;
                   protected String     Employee;
                   protected String     Rep;
                   protected String     Asst;
                   protected String     Client;
                   protected String     Dates;
                   protected String     Status;
                   protected String     Home;
                   public DBO_Referrals(long id) {
                        this.id = id;
                        Employee = "Employee" + id;
                        Rep = "Rep" + id;
                        Asst = "Asst" + id;
                        Client = "Client" + id;
                        Dates = "Dates" + id;
                        Status = "Status" + id;
                        Home = "Home" + id;
                   public long getId() {
                        return id;
                   public String getEmployee() {
                        return Employee;
                   public String getRep() {
                        return Rep;
                   public String getAsst() {
                        return Asst;
                   public String getClient() {
                        return Client;
                   public String getDates() {
                        return Dates;
                   public String getStatus() {
                        return Status;
                   public String getHome() {
                        return Home;
              public class ReferralsTableModel extends AbstractTableModel {
                   protected Vector<DBO_Referrals>          data          = new Vector<DBO_Referrals>();
                   protected String[]                         sColumns     = {"id", "Employee", "Rep", "Assistant", "Client", "Date", "Status", "Home", "R"};
                   public ReferralsTableModel() {
                        super();
                   public ReferralsTableModel(Vector<DBO_Referrals> data) {
                        this();
                        this.data = data;
                   @SuppressWarnings("unchecked")
                   @Override
                   public Class getColumnClass(int col) {
                        switch (col) {
                             case 0 :
                                  return Long.class;
                             default :
                                  return String.class;
                   @Override
                   public int getColumnCount() {
                        return sColumns.length;
                   @Override
                   public int getRowCount() {
                        return data.size();
                   @Override
                   public Object getValueAt(int row, int col) {
                        if (row > data.size())
                             return null;
                        DBO_Referrals a = data.get(row);
                        switch (col) {
                             case 0 :
                                  return a.getId();
                             case 1 :
                                  return a.getEmployee();
                             case 2 :
                                  return a.getRep();
                             case 3 :
                                  return a.getAsst();
                             case 4 :
                                  return a.getClient();
                             case 5 :
                                  return a.getDates();
                             case 6 :
                                  return a.getStatus();
                             case 7 :
                                  return a.getHome();
                             case 8 :
                                  return "+";
                             default :
                                  return null;

    BTW instead of continually printing out the memory use a profiler (jvisualvm in the jdk/bin directory -> heapdump -> search on your class -> view in instances -> find nearest GC root).
    Looks like BasicPopupMenuUI doesn't remove a reference to the JRootPane immediately. As far as I can see it will be removed when another menu shows.
    As a hackish workaround you can try this in you FrmReferrals#uninit():
                for(ChangeListener listener : MenuSelectionManager.defaultManager().getChangeListeners()) {
                    if (listener.getClass().getName().contains("MenuKeyboardHelper")) {
                        try {
                            Field field = listener.getClass().getDeclaredField("menuInputMap");
                            field.setAccessible(true);
                            field.set(listener, null);
                        } catch (Exception e) {
                            // ignored
                        break;
                }Funnily enough though it isn't there when I reduce your code to a SSCCE:
    import java.awt.*;
    import javax.swing.*;
    public class TestBasicPopupMenuUILeak extends JFrame {
        public TestBasicPopupMenuUILeak() {
            super("Not collected right away");
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(
                            new JButton(new AbstractAction("Show frame") {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    EventQueue.invokeLater(new Runnable() {
                                        public void run() {
                                            JLabel label = new JLabel(
    "Right click to show popup, then close this frame."
    + "The frame with not be GCed until another (popup) menu is shown.");
                                            JPopupMenu popup = new JPopupMenu(
                                                    "Popup");
                                            popup.add("Item");
                                            label.setComponentPopupMenu(popup);
                                            // named differently so you can find it
                                            // easily in your favorite profiler
                                            JFrame frame = new TestBasicPopupMenuUILeak();
                                            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                                            frame.getContentPane().add(label);
                                            frame.pack();
                                            frame.setLocationRelativeTo(null);
                                            frame.setVisible(true);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }

  • JPopupMenu with multiline JMenuItem ?

    Hi there.
    Is it possible to do something like the subject says, a JPopupMenu with multiline JMenuItem's, without using html? I would like to create a JMenuItem with a MultiLineLabel as the argument instead of a String. I'm trying to do this because if i add the MultiLineLabel directly to the JPopupMenu, it displays as i want, but i loose the behaviour inherent to a JMenuItem, the highlighted index, etc.. Any help would be appreciated.

    Here's a workaround:
    JPopupMenu popupMenu = new JPopupMenu();
    // Workaround to stop first menu item being selected
    JMenuItem dummyItem = popupMenu.add(new JMenuItem());
    dummyItem.setPreferredSize(new Dimension(0, 0));
    popupMenu.add("Item 1");
    popupMenu.add("Item 2");
    popupMenu.add("Item 3");
    It works for me!

  • Jpopupmenu visibility problem with JWindows

    Hello,
    BACKGROUND:
    I am attempting to implement a feature similar to one found in the netbeans IDE for a programming editor I am helping to write. The feature is an autocomplete/function suggestion based on the current word being typed, and an api popup for the selected function.
    Currently a JPopupMenu is used to provide a list of suggested functions based on the current word being typed. EG, when a user types 'array_s' a JPopupMenu pops up with array_search, array_shift, array_slice, etc.
    When the user selects one of these options (using the up/down arrow keys) a JWindow (with a jscrollpane embedded in it) is made visible which displays the api page for that particular function.
    PROBLEM:
    The problem is that when a user scrolls down the JWindow the JPopupmenu disappears so he user cannot select another function.
    I have added a ComponentListener to the JPopupMenu so that when componentHidden is called I can do checks to see if it should be visible and make visible if necessary. However, componentHidden is never called.
    I have added a focuslistener to the JPopupMenu so that when it loses focus I can do the same checks/make visible if necessary. This function is never called.
    I have added a popupMenuListener but this tells me when it is going to make something invisible, not actually when it's done it, so I can't call popup.setVisible(true) from popupMenuWillBecomeInvisible because at that point the menu is still visible.
    Does anyone have any suggestions about how I can scroll through a scrollpane in a JWindow whilst still keeping the focus on a separate JPopupMenu in a separate frame?
    Cheers

    The usual way to do popup windows (such as autocomplete as you're doing) is not to create a JPopupMenu, but rather an undecorated (J)Window. Stick a JList in the popup window for the user to select their choice from. The problem with using a JPopupMenu is just what you're experiencing - they're designed to disappear when they lose focus. Using an undecorated JWindow, you can control when it appears/disappears.
    See this thread for information on how to do this:
    http://forum.java.sun.com/thread.jspa?threadID=5261850&messageID=10090206#10090206
    It refers you to another thread describing how to create the "popup's" JWindow so that it doesn't steal input focus from the underlying text component. Then, further down, it describes how you can forward keyboard actions from the underlying text component to the JWindow's contents. This is needed, for example, so the user can keep typing when the autocomplete window is displayed, or press the up/down arrow keys to select different items in the autocomplete window.
    It sounds complicated, but it really isn't. :)

  • AWT PopupMenu not showing Chinese Characters

    Hi all.
    I have a mostly Swing application that must display English and Chinese characters. Changing the Swing components has been easy, however I am having problems changing an AWT PopupMenu that i use in combination with the new TrayIcon features of Java 6. TrayIcon requires an awt PopupMenu, so i cannot use a Swing JPopupMenu even if i wanted to.
    The problem is that instead of the correct words i am getting just empty squares, which seem to indicate a problem. I have tried setting the font to "SimSun" but this made no difference.
    I also tried this hack to use a JPopupMenu with Trayicon
    http://weblogs.java.net/blog/ixmal/archive/2006/05/using_jpopupmen.html
    This correctly showed the Chinese characters but it threw up lots of 'class cast' exceptions.
    My ideal solution would be to fix the problems with PopupMenu as apposed to fixing the class cast exception errors with the JPopMenu hack.
    Would anyone know why i cannot display Chinese characters in a AWT PopupMenu? have i missed something?
    Thanks
    Steven

    hi!
    check this out
    package com.ani;
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JLabel;
    public class showHindi extends Panel
         public showHindi()
              setLayout(new BorderLayout());
              String unicodeText = "\u0928\u092e\u0938\u094D\u0924\u0947";
              Font fn = new Font("Arial Unicode MS", Font.PLAIN, 32);
              Label lblText = new Label(unicodeText) {
                   @Override
                   public void paint(Graphics g)
                        //super.paint(g);
                        g.clearRect(0, 0, getWidth(), getHeight());
                        String str = getText();
                        g.drawChars(str.toCharArray(), 0, str.length(), 0, 30);
                        //System.out.println(getText());
              lblText.setFont(fn);
              JLabel lblText1 = new JLabel(unicodeText);
              lblText1.setFont(fn);
              add(lblText, BorderLayout.NORTH);
              add(lblText1, BorderLayout.SOUTH);
         public static void main(String[] args)
              Frame frm = new Frame("Test Hindi");
              frm.add(new showHindi());
              frm.setSize(600, 400);
              frm.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              frm.setVisible(true);
    }this is working in my machine. i have used JLabel and Label both to just show you the difference. there is a flickering bug because of rendering, i hope you can manage that.
    regards
    Aniruddha

  • JPopupMenu won't die

    Hi,
    I'm using a JPopupMenu on a JList and I'm experiencing an odd problem.
    The menu never actually closes itself under a certain circumstance.
    Say for instance you invoke the popup menu. If you click outside the frame, the menu closes fine. However, if you minimize the frame while the popup menu is displayed, things get weird when you restore it. The menu is still there, but in the form of a solid gray box. All lettering is gone and no highlighting occurs if I move the cursor over it. I have to invoke the popup menu again with a right click if I want the thing to actually disappear.
    I have dug through the forums in an attempt to find a solution. I didn't find anything that addressed my specific problem, but found things that might apply. None have worked. I have tried the following:
    popupMenu.setVisible(false);
    MenuSelectionManager.defaultManager().clearSelectedPath();
    remove(popupMenu);
    Is this a bug, or am I doing something incorrectly?
    Thanks for your help.

    Thank you for your reply. I tried your suggestion, but got the same results. I have coded up a demo program that will reproduce the problem. In addition, those who are interested can (for now) view screen caps of this issue at http://marble.sru.edu/~kjl4608/jpopupmenu.html
    Thanks for your help
    Demo - test.java:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class test extends JFrame
       private Container container;
       private JPopupMenu popupMenu;
       private DefaultListModel listModel;
       private JList list;
       public test()
          super("DEMO");
          setSize(100,210);
          container=getContentPane();
          container.setLayout(new BorderLayout());
          listModel=new DefaultListModel();
          doList();
          createPopupMenu();
       public static void main(String[] args)
          test frame=new test();
          frame.show();
       private void createPopupMenu()
          popupMenu=new JPopupMenu();
          for(int i=1;i<5;i++)
             popupMenu.add(new JMenuItem("Choice "+i));
          MouseListener popupListener=new popupListener();
          list.addMouseListener(popupListener);
       private void doList()
          for(int i=1;i<=10;i++)
             listModel.addElement("Item"+i);
          list=new JList(listModel);
          container.add(list,BorderLayout.CENTER);
       //class is nested
       private class popupListener extends MouseAdapter
          public void mousePressed(MouseEvent e)
          {  maybeShowPopup(e);  }
          public void mouseReleased(MouseEvent e)
          {  maybeShowPopup(e); }
          private void maybeShowPopup(MouseEvent e)
             if(e.isPopupTrigger())
                popupMenu.show(e.getComponent(),e.getX(),e.getY());
                int row=list.locationToIndex(e.getPoint());
             list.setSelectedIndex(row);
    }

  • Change background color in a JPopupMenu?

    Hello. I've been trying to change the background color of a JPopupMenu, so far with no success.
    I've tried:
    + invoke setBackground() along with setOpaque()
    + subclass JPopupMenu and provide the following method:
         public void paintComponent(Graphics g) {
              g.setColor(new Color(0,0,0));
              g.fillRect(0, 0,100,100);
              super.paintComponent(g);
         (Ignore the numbers in fillRect() -- I'm just trying to see any effect at all!)
    + change the relevant(??) properties in the UIManager:
         UIManager.getDefaults().put("PopupMenu.background",Color.BLUE);
         UIManager.put("PopupMenu.background",Color.BLUE);
         SwingUtilities.updateComponentTreeUI(c);
         updateUI();
         (and various combinations of similar things).
    OK, none of these seems to have any effect whatsoever. In case it matters, I am using Java 1.4.1 on Mac OSX.
    Thanks heaps for any guidance here.

    JPopupMenu just handles its JMenuItems.
    A JMenuItem is what gets painted, you can
    directly set the background color. When the
    item is selected it gets the LAF color.
    For example, change PopupMenuDemo with
        public void createPopupMenu() {
            JMenuItem menuItem;
         // set selection color before creating the items
         UIManager.put("MenuItem.selectionBackground", Color.pink); // <=== add this
            //Create the popup menu.
            JPopupMenu popup = new JPopupMenu();
            menuItem = new JMenuItem("A popup menu item");
            menuItem.setBackground(Color.red); // <=== add this
            menuItem.addActionListener(this);
            popup.add(menuItem);
            menuItem = new JMenuItem("Another popup menu item");
            menuItem.setBackground(Color.red); // <=== add this
            menuItem.addActionListener(this);
            popup.add(menuItem);
            //Add listener to the text area so the popup menu can come up.
            MouseListener popupListener = new PopupListener(popup);
            output.addMouseListener(popupListener);
        }

  • JPopupMenu won't go away when application is moved

    Sorry, I have to reask this question. I am pretty much stuck with this.
    I have JPopupMenu that contains a JScrollPane that has a JPanel inside it.
    My application's main component is a JFrame, the above JPopupMenu is part of a search panel (JPanel). Every time when I make JPopupMenu visible, then left-click on application's title bar, and move the whole application away, JPopupMenu stays in the original position! If I click on any other place, such as tool bar, or any other component, JPopupMenu will disappear.
    This is really strange stuff. My guess is that titile bar cannot detect mouse events? Is that true? Is there any way I can make it disappear once user holds title bar and move the whole application away?
    thanks in advance!
    Message was edited by:
    jack_wns

    Finally created some sample code I can use to explain the possible solution I try to figure out. If I run the same application and then right-click on the
    application, a popup menu will show up. If I move mouse outside the frame (I try to make JComponent visible so that I can move mouse outside JComponent, but I cannot make it happen), popup menu is still visible. I try to add the following to mouseExited method:
    popupMenu.setVisible(false);
    But this seemingly will disable pupup menu.
    What I try to do is: make popup disappear once user move her mouse outside frame (better yet JComponent). How can I do this?
    Here is the sample code I just created:
    import java.awt.AWTEvent;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    class PopupTest extends JComponent implements ActionListener, MouseListener {
         private JPanel topPanel;
         private JPopupMenu popupMenu;
         public PopupTest() {
              //setTitle("Popup Menu Application");
              setSize(310, 130);
              setBackground(Color.GREEN);
              topPanel = new JPanel();
              topPanel.setLayout(null);
              add(topPanel);
              JMenuItem menuFileNew = new JMenuItem("New");
              JMenuItem menuFileOpen = new JMenuItem("Open...");
              JMenuItem menuFileSave = new JMenuItem("Save");
              JMenuItem menuFileSaveAs = new JMenuItem("Save As...");
              JMenuItem menuFileExit = new JMenuItem("Exit");
              // Create a popup menu
              popupMenu = new JPopupMenu("Menu");
              popupMenu.add(menuFileNew);
              popupMenu.add(menuFileOpen);
              popupMenu.add(menuFileSave);
              popupMenu.add(menuFileSaveAs);
              popupMenu.add(menuFileExit);
              topPanel.add(popupMenu);
              enableEvents(AWTEvent.MOUSE_EVENT_MASK);
              menuFileNew.addActionListener(this);
              menuFileOpen.addActionListener(this);
              menuFileSave.addActionListener(this);
              menuFileSaveAs.addActionListener(this);
              menuFileExit.addActionListener(this);
              addMouseListener(this);
         public void processMouseEvent(MouseEvent event) {
              if (event.isPopupTrigger()) {
                   popupMenu.show(event.getComponent(), event.getX(), event.getY());
              super.processMouseEvent(event);
         public void actionPerformed(ActionEvent event) {
              System.out.println(event);
         public void mouseExited(final MouseEvent e) {
              System.out.println("Mouse Exited...");
              //popupMenu.setVisible(false);  //line added
         public void mouseEntered(final MouseEvent e) {
              System.out.println("Mouse Entered...");
         public void mousePressed(final MouseEvent e) {
              System.out.println("Mouse pressed...");
         public void mouseReleased(final MouseEvent e) {
         public void mouseClicked(final MouseEvent e) {
              System.out.println("Mouse Clicked...");
         public static void main(String args[]) {
              PopupTest mainFrame = new PopupTest();
              mainFrame.setVisible(true);
              JFrame frame = new JFrame();
              frame.setTitle("Popup Menu Application");
              frame.setSize(500, 430);
              frame.getContentPane().add(mainFrame);
              frame.setVisible(true);
    }thx

  • Menuicons not possible within Mustang-Trayicon-implementation ?

    The example on http://java.sun.com/developer/technicalArticles/J2SE/Desktop/mustang/systemtray/#moreinfo displays two menuitems with icons.
    I think that screenshot was not taken from the current mustang-version because I do not find a way to place an icon into a menuitem.
    The examples only show the general way to implement a trayicon which does not use the shown functionality.
    The class java.awt.MenuItem does not know anything about icons.
    Is there any way to create a trayicon with icons with current mustang-version ?

    I am affraid that it is impossilbe :(.
    I worked on this subject many days.
    Screenshot are probably from JDIC (JDesktop Integration Components , +2MB to your project) or it is JPopupMenu with no keyboard focus (so it does not disappear when user click somewhere else).
    You can show manually JPopupMenu, and make it above taskbar (!) ... but I could not find how to get keyboard input / focus.
    Pleas see my other post for more informations http://forums.java.net/jive/thread.jspa?threadID=23466&tstart=0 .
    There you can also get (and run) my simple example to check if your GUI hangs when you pop up tray icon menu.
    Write to me, or here, if you find any interesting solutions.
    Thanks!

  • Right click with Jlist

    Hi guys,
    I get the wrong ID with the code below.
    The error accours when the user right click on the name on the JList.
    (Basically, when the user right click the name he get a JTextArea with the associated ID)
    anyone?
            private class popupListener extends MouseAdapter
               public void mousePressed(MouseEvent e)
                    //showPopup(e); 
               public void mouseReleased(MouseEvent e)
                    showPopup(e); 
               private void showPopup(MouseEvent e)
                   if(e.isPopupTrigger())
                         if (list.getSelectedIndex()>=0)
                              popupMenu.removeAll();
                          HotelTravelerName hn  = (HotelTravelerName)  model.getElementAt(list.getSelectedIndex());               
                          JTextArea jta = new JTextArea();    
                        String msg = "\nID:"+hn.getID()+"\n";
                        jta.setText(msg);
                        popupMenu.add(jta);
                                popupMenu.show(e.getComponent(),e.getX(),e.getY());
                              int row=list.locationToIndex(e.getPoint());
                              list.setSelectedIndex(row);                   
            }

    here it is:
    * note: if you double click the item and than right-click - it's good. but when right clicking the item - the returned value is wrong.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class test extends JFrame
       private Container container;
       private JPopupMenu popupMenu;
       private DefaultListModel listModel;
       private JList list;
       public test()
          super("DEMO");
          setSize(100,210);
          container=getContentPane();
          container.setLayout(new BorderLayout());
          listModel=new DefaultListModel();
          doList();
          MouseListener popupListener=new popupListener();
          list.addMouseListener(popupListener);
       public static void main(String[] args)
          test frame=new test();
          frame.show();
       private void doList()
          for(int i=0;i<10;i++)
             listModel.addElement("Item"+i);
          list=new JList(listModel);
          container.add(list,BorderLayout.CENTER);
       //class is nested
       private class popupListener extends MouseAdapter
          public void mousePressed(MouseEvent e)
          {  maybeShowPopup(e);  }
          public void mouseReleased(MouseEvent e)
          {  maybeShowPopup(e); }
          private void maybeShowPopup(MouseEvent e)
             if(e.isPopupTrigger())
                 popupMenu=new JPopupMenu();            
                 popupMenu.add(new JTextField("You have chosen item number "+list.getSelectedIndex()));                     
                 popupMenu.show(e.getComponent(),e.getX(),e.getY());
                 int row=list.locationToIndex(e.getPoint());
                 list.setSelectedIndex(row);
    }

  • Add popupMenu to the elements of a jToolBar

    Hi all,
    I'm trying to add a popupMenu to the images that I have in a jToolBar. So my idea is to show the popupMenu when the user clicks with the secondary mouse button in one of the images. When the user clicks with the primary mouse button the application does another action. I have the ThumbnailAction class that implements it:
    private class ThumbnailAction extends AbstractAction
    *The icon if the full image we want to display.
    private Icon displayPhoto;
    private JPopupMenu jPopupMenu1 = new JPopupMenu();
    private JPanel topPanel;
         private     JPopupMenu popupMenu;
    * @param Icon - The full size photo to show in the button.
    * @param Icon - The thumbnail to show in the button.
    * @param String - The descriptioon of the icon.
    public ThumbnailAction(Icon photo, Icon thumb, String desc){
    topPanel = new JPanel();
              topPanel.setLayout( null );
              getContentPane().add( topPanel );
              // Create some menu items for the popup
              JMenuItem menuFileNew = new JMenuItem( "New" );
              JMenuItem menuFileOpen = new JMenuItem( "Open..." );
              JMenuItem menuFileSave = new JMenuItem( "Save" );
              JMenuItem menuFileSaveAs = new JMenuItem( "Save As..." );
              JMenuItem menuFileExit = new JMenuItem( "Exit" );
              // Create a popup menu
              popupMenu = new JPopupMenu( "Menu" );
              popupMenu.add( menuFileNew );
              popupMenu.add( menuFileOpen );
              popupMenu.add( menuFileSave );
              popupMenu.add( menuFileSaveAs );
              popupMenu.add( menuFileExit );
              topPanel.add( popupMenu );
              // Action and mouse listener support
              enableEvents( AWTEvent.MOUSE_EVENT_MASK );
              menuFileNew.addActionListener( this );
              menuFileOpen.addActionListener( this );
              menuFileSave.addActionListener( this );
              menuFileSaveAs.addActionListener( this );
              menuFileExit.addActionListener( this );
    // displayPhoto = photo;
    // The short description becomes the tooltip of a button.
    putValue(SHORT_DESCRIPTION, desc);
    // The LARGE_ICON_KEY is the key for setting the
    // icon when an Action is applied to a button.
    putValue(LARGE_ICON_KEY, thumb);
    public void processMouseEvent( MouseEvent event )
    System.out.println("entra aki cony!");
              if( event.isPopupTrigger() )
                   System.out.println("is popup!");//popupMenu.show( event.getComponent(), event.getX(), event.getY() );
              this.processMouseEvent( event );
    * Shows the full image in the main area and sets the application title.
    public void actionPerformed(ActionEvent e) {
    System.out.println("hay evento");
    photographLabel.setIcon(displayPhoto);
    /* Executable ex = null;
    try {
    ex.openDocument("C:/Documents and Settings/Administrador/iText/src/com/lowagie/tools/PDF's/pdf3.pdf");
    } catch (IOException exc) {
    exc.printStackTrace();
    StringTokenizer st = new StringTokenizer (getValue(SHORT_DESCRIPTION).toString());
    actualPDF =st.nextToken(". ");
    actualPDF += ".pdf";
    setTitle("Selected document: " + actualPDF);
    The problem I have is that the app never goes to processMouseEvent(), I think I have problems with the inheritance or sth else. It would be thankful if somebody can help me, please!!!
    Thanks in advance!!!

    If you want your video to play on anywhere then you don't want Flash. You should be able to use a simple html5 page to play your video and then redirect the user to a new page, or display a new div to get to the form. Here's a good discussion of doing that sort of thing: http://help.videojs.com/discussions/questions/509-videojs-and-passing-an-event-at-the-end- of-the-video You can also look at the regular html video dom reference: http://www.w3schools.com/tags/av_prop_ended.asp

Maybe you are looking for

  • Purchase Order required at PGI Level in the delivery

    Dear Gurus, I am having the following problem: When I want to make Post Goods Issue at delivery level (VL01), the system prompts me for a Purchase Order Number. I have updated the stock in 2009 and I have checked that there are sufficient quantities

  • ALL-PHOTOS-VIDEOS buttons don't work in iOS app

    Hi there! I just downloaded the Revel iOS app which I found amazing! The best memories cloud storage solution I've found so far! I found an issue with the app, when watching all the photos in a library, the ALL PHOTOS VIDEOS buttons don't work at all

  • Can we make the SELECTION CRITERIA BOX act as a Menu / Submenu system?

    Dear All, I have written several queries. For user convenience, I wish to combine all related queries in a single Query and use the Selection Criteria box as a Menu System to select which Query script to run. I can already do this by the use of varia

  • Namespace

    Hello, Because tables and views are in the same namespace, a table and a view in the same schema cannot have the same name. However, tables and indexes are in different namespaces. Therefore, a table and an index in the same schema can have the same

  • Transfer purchased songs from one computer to another

    I bought 6 songs on my laptop due to a better internet connection. I want to transfer them to my desktop computer. When I log in, it has all my old songs listed, not the one's that I bought from my laptop and my old songs together. How can I merge th