Show PopupMenu in JMenuItem

I want to show the popupmenu when users do the right click on the
menuitem to do something like the mozilla or internet explorer
Favorites menu which can be do right click to show the popup.
I tried this, but i always have the following problems:
java.lang.NullPointerException
at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.grabContainer(Unknown Source)
at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.requestAddGrab(Unknown Source)
at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.stateChanged(Unknown Source)
at javax.swing.MenuSelectionManager.fireStateChanged(Unknown Source)
at javax.swing.MenuSelectionManager.setSelectedPath(Unknown Source)
at javax.swing.JPopupMenu.setVisible(Unknown Source)
at javax.swing.JPopupMenu.show(Unknown Source)
at test.jessy.menu.TestSimplePopup$1.mousePressed(TestSimplePopup.java:34)
This is my test code, I can compile and run it. But the error occurs
when I do the right mouse click on the "http://java.sun.com" jmenuitem
of this code. Aims to show the popup window and this menuitem still
stay show. Thanks for your help.
==============================================================
public class TestSimplePopup extends JFrame{
JPopupMenu popupMenu;
public TestSimplePopup() {
super();
//create popupmenu.
popupMenu = new JPopupMenu();
popupMenu.add( new JMenuItem("delete this link"));
popupMenu.add( new JMenuItem("go to this link"));
//create menubar.
JMenuBar menuBar = new JMenuBar();
//create favoritemenu.
JMenu favoriteMenu = new JMenu("Favorite");
JMenuItem link1 = new JMenuItem("http://java.sun.com");
link1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
if( SwingUtilities.isRightMouseButton(e) ){
//right-click
popupMenu.show(e.getComponent(), e.getX(), e.getY());
} else {
System.out.println( "left click=" + e.getSource() );
favoriteMenu.add( link1 );
menuBar.add( favoriteMenu );
setJMenuBar( menuBar );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
show();
public static void main(String[] args) {
new TestSimplePopup();
==============================================================

First:
please use code-tags when posting code. You should now this (its your 9th post after all).
Second:
I believe the NullPointerException is thrown because the popupMenu itself does not have a Window ancestor (I debugged your code). How to set the ancestor of your popupMenu to your JFrame I am not sure. JFrame has an add(PopupMenu) but not add(JPopupMenu).
Perhaps someone else can help you further.

Similar Messages

  • PopupMenu in JMenuItem

    Hi. I have a JMenu which has several JMenuItems added to it. When an item is right-clicked, I would like a JPopupMenu to be displayed. This can be done by creating a custom MenuUI and only firiing actions on left clicks and showing the popup menu on right-click.
    The problem is that when the popup menu appears the underlying menu disappears, which I do not want to happen (I'm trying to achieve the effect of a favorites menu in a web browser where you can right click a favorite item and edit, delete, etc).
    Does anyone have a good way to do this?
    Thanks,
    Jeff

    This is the only way I can think of, but it's a nasty hack.
    You can add your popup code in the else of the if in mousePressed.
    setUI(new BasicMenuUI() {
        MouseInputListener listener;
        protected MouseInputListener createMouseInputListener(JComponent c) {
            listener = super.createMouseInputListener(c);
            return new MouseInputListener() {
                public void mouseClicked(MouseEvent e) {
                    listener.mouseClicked(e);
                public void mousePressed(MouseEvent e) {
                    if (!(e.getButton() == MouseEvent.BUTTON3))
                        listener.mousePressed(e);
                public void mouseReleased(MouseEvent e) {
                    listener.mouseReleased(e);
                public void mouseEntered(MouseEvent e) {
                    listener.mouseEntered(e);
                public void mouseExited(MouseEvent e) {
                    listener.mouseExited(e);
                public void mouseDragged(MouseEvent e) {
                    listener.mouseDragged(e);
                public void mouseMoved(MouseEvent e) {
                    listener.mouseMoved(e);
    });

  • JPopupMenu showing only last JMenuItem

    Hello,
    I have a strange problem with JPopupMenu - only 1 JMenuItem (last one) is shown in the menu although there are 2 of them there.
    Menu is created by following sequence:
    JPopupMenu popup = new JPopupMenu;
    JMenuItem item1 = new JMenuItem();
    item.setText( "ft" );
    popup.add( item1 );
    JMenuItem item2 = new JMenuItem();
    item.setText( "m" );
    popup.add( item2 );
    Menu is activated (shown) after a button is pressed in the code called from button ActionListener:
    // parameter is ActionEvent aEvent
    popup.show( ( Component ) aEvent.getSource(), 0, 0 );
    popup.pack(); // does not affect the behaviour, if omitted
    // dubugging: trying to make sure menu has more than 1 element           
    MenuElement[] elems = popup.getSubElements();
    for( MenuElement elem: elems )
    System.out.println( elem );
    The code works, menu appears, but only with last item.
    The debug printout shows, that menu has 2 elements:
    javax.swing.JMenuItem[,0,0,0x0,layout=java.awt.BorderLayout,alignmentX=0.0,align
    mentY=0.0,border=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@3b1f38,flags
    =264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disable
    dSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,ri
    ght=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,roll
    overIcon=,rolloverSelectedIcon=,selectedIcon=,text=ft]
    javax.swing.JMenuItem[,1,3,39x20,layout=java.awt.BorderLayout,alignmentX=0.0,ali
    gnmentY=0.0,border=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@3b1f38,fla
    gs=264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disab
    ledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,
    right=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,ro
    lloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=m]
    Do you have an idea, why just last item is shown ?
    When I changed
    popup.show( ( Component ) aEvent.getSource(), 0, 0 );
    to
    popup.show( mainFrame, 0, 0 );
    the menu appeared in the new location, but on change of behaviour ( my first idea was, that menu is clipped to the size of button).
    Thanks.
    Martin

    Don't show us bits and pieces of code. Show us a demo program of how you are creating and attempting to show the popup menu. The code you post may not be related to the problem.
    Also, don't forget to use the "formatting tags" so the code retains its original formatting.

  • Show popupmenu on title of tab pane

    hi..
    can somebody help me?
    how to show a popupmenu when user clicks on the title of a tab pane?
    thx

    Just install a mouse listener and when you recive
    an event show the popmenu.
    To check that a mouse event occured on a tab:
    int index = tabPane.getUI().tabForCoordinate(tabPane, event.getX(), event.getY());
    if (index != -1) {
    //mouse click on tab
    That should do the trick.
    lp

  • Problem with Show Popup Menu in Dreamweaver 8

    I am trying to add the behavior show pop up menu to
    an image. When I try to I get the error While executing onLoad in
    ShowPopup Menu.js the JavaScript error occurred at line 2015 of the
    file ....Show PopupMenu.js type error
    dw.getNaturalSize(getFullPath(selobj.scr)) has no properties. How
    can I fix this I have tried everything I know Thanks Stuck2

    These pop-up menus as implemented in DW are quite bad, and
    while your error
    is most likely unrelated to your use of the menus, I felt I
    had to warn you
    that their use leads to a wasteland of failed efforts. There
    are much
    better ways.
    You can try this simple fix -
    Quit DW.
    Find this folder -
    C:\Documents and Settings\<username>\Application
    Data\Macromedia\Dreamweaver
    8\Configuration\WinFileCache-*.dat
    (these folders are normally hidden - you may have to use
    Explorer > Tools >
    Folder Options to unhide them)
    or on Mac -
    Library/Application Support/Macromedia/Dreamweaver
    8/Configuration/MacFileCache-*.dat
    and delete it.
    Restart DW. Works better?
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "STUCK2" <[email protected]> wrote in
    message
    news:ehnv6g$k17$[email protected]..
    >
    I am trying to add the behavior show pop up menu to
    an image.
    > When I
    > try to I get the error While executing onLoad in
    ShowPopup Menu.js the
    > JavaScript error occurred at line 2015 of the file
    ....Show PopupMenu.js
    > type
    > error dw.getNaturalSize(getFullPath(selobj.scr)) has no
    properties. How
    > can I
    > fix this I have tried everything I know Thanks Stuck2
    >

  • JPopupMenu/JMenuItem sizing problem

    Hi All,
    I have a JPopupMenu that is displayed when a right-click takes place. The popup menu should display three JMenuItems when a vertex is right-clicked and one menu item when an edge is right-clicked. However, when I right-click a vertex, only two menu items are visible, and when I right-click an edge, zero menu items are visible (the popup menu appears, but it is so small that I can't see the menu item).
    Here is the relevant code:
              protected void handlePopup(MouseEvent me) {
                final VisualizationViewer vv = (VisualizationViewer)me.getSource();
                Point2D p = vv.inverseViewTransform(me.getPoint());
                PickSupport pickSupport = vv.getPickSupport();
                if(pickSupport != null) {
                    Vertex v = pickSupport.getVertex(p.getX(), p.getY());
                    Edge e = pickSupport.getEdge(p.getX(), p.getY());
                    if((v != null) && (v instanceof BrokerVertex)) {                 
                         JPopupMenu popup = new JPopupMenu();
                        JMenuItem m_SetAdvMenuItem = new JMenuItem(MonitorResources.M_SET_ADV);
                        m_SetAdvMenuItem.addActionListener(m_MonitorFrame);
                        popup.add(m_SetAdvMenuItem);
                        JMenuItem m_centerVertex = new JMenuItem("Center Vertex");
                        m_centerVertex.setAction(new CenterAction(m_graph.getLayout().getLocation(v)));
                        popup.add(m_centerVertex);
                        JMenuItem m_SetSubMenuItem = new JMenuItem(MonitorResources.M_SET_SUB);
                        m_SetSubMenuItem.addActionListener(m_MonitorFrame);
                        popup.add(m_SetSubMenuItem);
                        popup.show(vv, me.getX(), me.getY());
                        popup.pack();
                    } else if ((e != null) && (e instanceof MonitorEdge)) {
                         MonitorEdge mEdge = (MonitorEdge) e;
                         JPopupMenu popup = new JPopupMenu();
                         boolean activationCountDisplayStatus = mEdge.activationCountIsDisplayed();
                         String activationCountToggleMessage;
                         if (activationCountDisplayStatus) {
                              activationCountToggleMessage = "Hide Message Counter";
                         } else {
                              activationCountToggleMessage = "Show Message Counter";
                        JMenuItem m_activationCountMenuItem = new JMenuItem(activationCountToggleMessage);
                        m_activationCountMenuItem.setAction(new ToggleEdgeActivationCountMessageAction(mEdge));
                        popup.add(m_activationCountMenuItem);
                        popup.show(vv, me.getX(), me.getY());
                        popup.pack();
              }The problem is with the JMenuItems that use setAction instead of addActionListener (m_centerVertex and m_activationCountMenuItem). These two JMenuItems are in the popup menu list, but the popup menu is not large enough for me to see the labels given to m_centerVertex and m_activationCountMenuItem.
    Anyone know what I'm doing wrong?
    m_SetAdvMenuItem and m_SetSubMenuItem display correctly. It's as if the height of m_centerVertex and m_activationCountMenuItem are set at a value of 0 but the heights of the other two JMenuItems are the correct height.
    Message was edited by:
    themiddle

    Did you set a name value in your Actions? The name value will be used to set the text. If its null that may account for the small size of the menu item.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Sub-Menus are displaying away from their parent Menu for first time.

    Hi All,
    I have a problem with sub-menus display location. In my application, I have a JPopupMenu to which several sub-menus (*JMenu*) are added. All the JMenuItems inside JMenu are having an Icon (Image) along with menu item title. I am providing a facility to change the font size of Menu Item names as well as the ImageIcon size dynamically through a dialog box. When the size is changed to larger value than the existing, the menus as well as submenus are getting displayed correctly. But when I change the size of ImageIcon and the font to smaller value than the existing one, then the submenus are getting displayed away from their parent menu for the first time. The location of sub menu display is matching with the location when their size was larger. This problem appears only for the first display of sub menus after their sizes are changed. For the successive display, the locating is resetting automatically to correct location.
    So can anybody help me out about how to display submenus at correct location irrespective of font and image size changes for the first time also? Is there any event which gets fired when we change the font size or ImageIcon sizes? Is there any specific method to refresh the menu sizes if any of such properties (such as font size, ImageIcon size) are changed?
    If you need any additional information, feel free to ask.

    Below is the sample code for the query I placed. Steps to reproduce the problem are:
    1. Click on "Increase Font" button.
    2. Generate the popup at the right side corner of the screen (using right mouse click) such that the sub menu of edit should appear at left side of "Edit" option.
    3. Click on "Decrease Font" button.
    4. Generate the popup at the right side corner of the screen (using right mouse click) such that the sub menu of edit should appear at left side of "Edit" option.
    You will see that sub menu of edit menu is displayed away from the popup for the first time. The sub menu location matches with previous location when its font size was larger. Location resets automatically for the next successive displays.
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    public class JPopupDemo implements ActionListener {
      public static Font newFont=new Font("Times New Roman", Font.BOLD,24);
      JFrame frame = null;
      JPopupMenu popupMenu = null;
      JMenuItem fileMenu = null;
      JMenu editMenu = null;
      JMenuItem cutMenuItem = null;
      JMenuItem copyMenuItem = null;
      JMenuItem pasteMenuItem = null;
      JMenuItem findMenuItem = null;
        JPopupDemo(){
        frame = new JFrame("Popup Example");     
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        popupMenu = new JPopupMenu();
        fileMenu = new JMenuItem("File");
        editMenu = new JMenu("Edit");
        cutMenuItem = new JMenuItem("Cut");
        editMenu.add(cutMenuItem);
        copyMenuItem = new JMenuItem("Copy");
        editMenu.add(copyMenuItem);
        pasteMenuItem = new JMenuItem("Paste");
        pasteMenuItem.setEnabled(false);
        editMenu.add(pasteMenuItem);
        editMenu.addSeparator();
        findMenuItem = new JMenuItem("Find");
        editMenu.add(findMenuItem);
        popupMenu.add(fileMenu);
        popupMenu.add(editMenu);
        MouseListener mouseListener = new JPopupMenuShower(popupMenu);
        frame.addMouseListener(mouseListener);
        //frame.setSize(350, 250);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dim = toolkit.getScreenSize();
        frame.setSize(dim.width,dim.height-100);
        JButton incrButton = new JButton("Increase Size");
        incrButton.setActionCommand("IncreaseSize");
        incrButton.addActionListener(this);
        JButton decrButton = new JButton("Decrease Size");
        decrButton.setActionCommand("DecreaseSize");
        decrButton.addActionListener(this);
        Container cp = frame.getContentPane();
        cp.setLayout(new BorderLayout());
        JPanel jp = new JPanel();
        jp.add(incrButton);
        jp.add(decrButton);
        cp.add(jp,BorderLayout.SOUTH);
        frame.setVisible(true);
    public static void main(String args[]) {
         JPopupDemo demo = new JPopupDemo();
      public void actionPerformed(ActionEvent ae)
            if (ae.getActionCommand().equals("IncreaseSize"))
                   newFont = new Font("Times New Roman", Font.BOLD,48);
                   setNewFont();
              else if (ae.getActionCommand().equals("DecreaseSize"))
                   newFont = new Font("Times New Roman", Font.BOLD,12);
                   setNewFont();
       public void setNewFont()
            popupMenu.setFont(newFont);
            fileMenu.setFont(newFont);
            editMenu.setFont(newFont);
            cutMenuItem.setFont(newFont);
            copyMenuItem.setFont(newFont);
            pasteMenuItem.setFont(newFont);
            findMenuItem.setFont(newFont);
    class JPopupMenuShower extends MouseAdapter {
      private JPopupMenu popup;
      public JPopupMenuShower(JPopupMenu popup) {
        this.popup = popup;
      private void showIfPopupTrigger(MouseEvent mouseEvent) {
        if (popup.isPopupTrigger(mouseEvent)) {
          popup.show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent
              .getY());
      public void mousePressed(MouseEvent mouseEvent) {
        showIfPopupTrigger(mouseEvent);
      public void mouseReleased(MouseEvent mouseEvent) {
        showIfPopupTrigger(mouseEvent);
    }Edited by: VPKVL on Aug 4, 2008 1:18 AM

  • 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

  • I have boxes instead of Farsi characters as the text of MenuItem label...

    Hi
    As i started programming by jdk6, i had no problem in text components neither in awt nor in swing.
    But for labels or titles of AWT components, yes :
    I couldn't have Farsi characters displayable on AWTs just as simple as Swing by typing them into the source code.
    lets check this SSCCE :
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Properties;
    public class EmptyFarsiCharsOnAWT extends JFrame{
        public EmptyFarsiCharsOnAWT() {
            super("&#1605;&#1579;&#1575;&#1604;");
            setDefaultCloseOperation(3);
            setVisible(rootPaneCheckingEnabled);
        public static void main(String[] args) throws AWTException, IOException {
            JFrame jFrame = new EmptyFarsiCharsOnAWT();
            MenuItem show ;
            // approach 1 = HardCoding :
            show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634 \u0645\u062a\u0627");
            // approach 2 = using simple utf-8 saved text file :
                BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt"));
                String showLabel = in.readLine();
                in.close();
                show = new MenuItem(showLabel);
             // approach 3 = using properties file :
            FileReader in = new FileReader("farsiLabels.properties");
            Properties farsiLabels = new Properties();
            farsiLabels.load(in);
            show = new MenuItem(farsiLabels.getProperty("tray.show"));
            PopupMenu popUp = new PopupMenu();
            popUp.add(show);
                // creating Tray object
                Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png");
                TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
                SystemTray tray = SystemTray.getSystemTray();
                tray.add(trayIcon);
                jFrame.setIconImage(iconIamge);
    Yes, i know each of three approaches in source code does right when you may test it from IDE , but if you make a JAR contains just this class (and its resources) by means of NetBeans > project > clean&build ,you won't see the expected characters and will just get EMPTY/BLANK SQUARES !
    Unfortunately, opposed to other situations i encountered before, here there is no way to avoid using awt and make use of Swing in this case.
    And this was just an SSCCE i made to show the problem and my recent (also first ) application suffers from this subject.
    Unfortunately it seems i can not attach anything to my post!
    the content of text file is just this one line:
    &#1606;&#1605;&#1575;&#1740;&#1588; &#1605;&#1578;&#1575;and
    The contents of Properties file is this :
    #Sun May 02 09:45:10 IRDT 2010  
    tray.show=&#65279;&#1606;&#1605;&#1575;&#1740;&#1588; &#1605;&#1578;&#1575;for instance.
    the icon image i don't think will differ to the issue.
    i am using latest version of Netbeans IDE.
    Thank you very much in advance.

    Any idea plz ?

  • Adding a JButton when there's a paint method

    I'm creating a game application, sort of like a maze, and I want to add buttons to the levelOne panel to be able to move around the maze. When I add the buttons to the panel they don't appear, I assume the paint method is the reason for this. here's my code, I have 3 files, ill post the user_interface, and the levels class, where the level is created and where i tried to add the button. I tried putting the buttons in a JOptionPane, but then my JMenu wouldn't work at the same time the OptionPane was opened. If anyone knows a way around this instead, please let me know. I also tried using a separate class with a paintComponent method in it, and then adding the button (saw on a forum, not sure if it was this one), but that didn't work either. Also, if there is a way just to simply have the user press the directional keys on the keyboard and have the program perform a certain function when certain keys are pressed, I'd like to know, as that would solve my whole problem. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
    static Levels l = new Levels ();
    static Delay d = new Delay ();
    private Container contentPane = getContentPane ();
    private JPanel main, levelOne;
    private String level;
    private CardLayout cc = new CardLayout ();
    private GridBagConstraints gbc = new GridBagConstraints ();
    private JPanel c = new JPanel ();
    private String label = "MainMenu";
    public User_Interface ()
    //Generates the User-Interface
    super ("Trapped");
    main = new JPanel ();
    GridBagLayout gbl = new GridBagLayout ();
    main.setLayout (gbl);
    c.setLayout (cc);
    // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
    c.add (main, "Main Page");
    contentPane.add (c, BorderLayout.CENTER);
    cc.show (c, "Main Page");
    levelOne = new JPanel ();
    levelOne.setLayout (new GridBagLayout ());
    levelOne.setBackground (Color.black);
    c.add (levelOne, "LevelOne");
    JMenuBar menu = new JMenuBar ();
    JMenu file = new JMenu ("File");
    JMenu help = new JMenu ("Help");
    JMenuItem about = new JMenuItem ("About");
    JMenuItem mainmenu = new JMenuItem ("Main Menu");
    mainmenu.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    cc.show (c, "Main Page");
    label = "MainMenu";
    JMenuItem newGame = new JMenuItem ("New Game");
    newGame.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    l.xCord = 2;
    l.yCord = 2;
    l.xLoc = 140;
    l.yLoc = 140;
    JPanel entrance = new JPanel ();
    entrance.setLayout (new FlowLayout ());
    c.add (entrance, "Entrance");
    label = "Entrance";
    level = "ONE";
    cc.show (c, "Entrance");
    JMenuItem loadgame = new JMenuItem ("Load Game");
    JMenuItem savegame = new JMenuItem ("Save Game");
    JMenuItem exit = new JMenuItem ("Exit");
    exit.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    JFrame frame = new JFrame ();
    frame.setLocation (10, 10);
    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
    System.exit (0);
    file.add (about);
    file.add (mainmenu);
    file.add (newGame);
    file.add (loadgame);
    file.add (savegame);
    file.add (exit);
    menu.add (file);
    menu.add (help);
    setJMenuBar (menu);
    //Sets the size of the container (columns by rows)
    setSize (750, 550);
    //Sets the location of the container
    setLocation (10, 10);
    //Sets the background colour to a dark blue colour
    main.setBackground (Color.black);
    //Makes the container visible
    setVisible (true);
    public void paint (Graphics g)
    super.paint (g);
    g.setColor (Color.white);
    if (label == "MainMenu")
    for (int x = 0 ; x <= 50 ; ++x)
    g.setColor (Color.white);
    g.setFont (new Font ("Arial", Font.BOLD, x));
    g.drawString ("T R A P P E D", 100, 125);
    d.delay (10);
    if (x != 50)
    g.setColor (Color.black);
    g.drawString ("T R A P P E D", 100, 125);
    if (label == "Entrance")
    l.Entrance ("ONE", g);
    label = "LevelOne";
    if (label == "LevelOne")
    l.LevelOne (g, levelOne, gbc);
    label = "";
    public static void main (String[] args)
    // calls the program
    User_Interface application = new User_Interface ();
    application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Levels extends Objects
    private JFrame frame = new JFrame ();
    //Sets location, size, and visiblity to the frame where the JOptionPane
    //will be placed
    frame.setLocation (600, 600);
    frame.setSize (1, 1);
    frame.setVisible (false);
    public int xCord = 2;
    public int yCord = 2;
    public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
    ***Trying to add the button, doesn't appear. Tried adding to the container, and any JPanel i had created***
    JButton button1 = new JButton ("TEST");
    one.add (button1);
    g.setColor (Color.white);
    g.fillRect (500, 100, 200, 300);
    g.setColor (Color.black);
    g.drawRect (500, 100, 200, 300);
    g.setFont (new Font ("Verdana", Font.BOLD, 25));
    g.setColor (Color.black);
    g.drawString ("LEVEL ONE", 525, 80);
    //ROW ONE
    counter = -80;
    counter2 = 200;
    for (int a = 1 ; a <= 7 ; ++a)
    if (xCord < a && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
    if (xCord > a - 1 && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
    counter += 40;
    counter2 += 40;
    *****Theres 9 more rows, just edited out to save space****
    int y = 100;
    int x = 100;
    for (int a = 0 ; a < 20 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    y += 40;
    if (a == 9)
    x += 320;
    y = 100;
    x = 140;
    y = 100;
    for (int a = 0 ; a < 14 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    x += 40;
    if (a == 6)
    x = 140;
    y += 360;
    g.setColor (Color.black);
    g.drawRect (100, 100, 360, 400);
    ImageIcon[] images = new ImageIcon [4];
    images [0] = new ImageIcon ("arrow_left.gif");
    images [1] = new ImageIcon ("arrow_up.gif");
    images [2] = new ImageIcon ("arrow_down.gif");
    images [3] = new ImageIcon ("arrow_right.gif");
    int direction = -1;
    *****This is where I tried to have the OptionPane show the directional buttons******
    //frame.setVisible (true);
    // direction = JOptionPane.showOptionDialog (frame, "Choose Your Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
    // JOptionPane.QUESTION_MESSAGE,
    // null,
    // images,
    // images [3]);
    // if (direction == 0)
    // if (xCord - 1 > 0)
    // xCord -= 1;
    // xLoc += 40;
    // if (direction == 1)
    // if (yCord - 1 > 0)
    // yCord -= 1;
    // yLoc += 40;
    // if (direction == 2)
    // if (yCord + 1 < 9)
    // yCord += 1;
    // yLoc -= 40;
    // if (direction == 3)
    // if (xCord + 1 < 13)
    // xCord += 1;
    // xLoc -= 40;
    //LevelOne (g, one, gbc);
    }

    i tried adding a keylistener, that didn't work too well, i had tried to add it to a button and a textarea which i added to the 'one' frame, it didn't show up, and it didn't work. How would i go about changing the paint method so that it doesn't contain any logic? That's the only way I could think of getting the program to move forward in the game. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
        static Levels l = new Levels ();
        static Delay d = new Delay ();
        private Container contentPane = getContentPane ();
        private JPanel main, levelOne;
        private String level;
        private CardLayout cc = new CardLayout ();
        private GridBagConstraints gbc = new GridBagConstraints ();
        private JPanel c = new JPanel ();
        private String label = "MainMenu";
        public User_Interface ()
            //Generates the User-Interface
            super ("Trapped");
            main = new JPanel ();
            GridBagLayout gbl = new GridBagLayout ();
            main.setLayout (gbl);
            c.setLayout (cc);
            // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
            c.add (main, "Main Page");
            contentPane.add (c, BorderLayout.CENTER);
            cc.show (c, "Main Page");
            levelOne = new JPanel ();
            levelOne.setLayout (new GridBagLayout ());
            levelOne.setBackground (Color.black);
            c.add (levelOne, "LevelOne");
            JMenuBar menu = new JMenuBar ();
            JMenu file = new JMenu ("File");
            JMenu help = new JMenu ("Help");
            JMenuItem about = new JMenuItem ("About");
            JMenuItem mainmenu = new JMenuItem ("Main Menu");
            mainmenu.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    cc.show (c, "Main Page");
                    label = "MainMenu";
            JMenuItem newGame = new JMenuItem ("New Game");
            newGame.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    l.xCord = 2;
                    l.yCord = 2;
                    l.xLoc = 140;
                    l.yLoc = 140;
                    JPanel entrance = new JPanel ();
                    entrance.setLayout (new FlowLayout ());
                    c.add (entrance, "Entrance");
                    label = "Entrance";
                    level = "ONE";
                    cc.show (c, "Entrance");
            JMenuItem loadgame = new JMenuItem ("Load Game");
            JMenuItem savegame = new JMenuItem ("Save Game");
            JMenuItem exit = new JMenuItem ("Exit");
            exit.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    JFrame frame = new JFrame ();
                    frame.setLocation (10, 10);
                    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);
            file.add (about);
            file.add (mainmenu);
            file.add (newGame);
            file.add (loadgame);
            file.add (savegame);
            file.add (exit);
            menu.add (file);
            menu.add (help);
            setJMenuBar (menu);
            //Sets the size of the container (columns by rows)
            setSize (750, 550);
            //Sets the location of the container
            setLocation (10, 10);
            //Sets the background colour to a dark blue colour
            main.setBackground (Color.black);
            //Makes the container visible
            setVisible (true);
        public void paint (Graphics g)
            super.paint (g);
            g.setColor (Color.white);
            if (label == "MainMenu")
                for (int x = 0 ; x <= 50 ; ++x)
                    g.setColor (Color.white);
                    g.setFont (new Font ("Arial", Font.BOLD, x));
                    g.drawString ("T    R    A    P    P    E    D", 100, 125);
                    d.delay (10);
                    if (x != 50)
                        g.setColor (Color.black);
                        g.drawString ("T    R    A    P    P    E    D", 100, 125);
            if (label == "Entrance")
                l.Entrance ("ONE", g);
                label = "LevelOne";
            if (label == "LevelOne")
                l.LevelOne (g, levelOne, gbc);
                label = "";
            //g.setColor (new Color
        public static void main (String[] args)
            // calls the program
            User_Interface application = new User_Interface ();
            application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.ActionMap;
    import javax.swing.plaf.*;
    public class Levels extends Objects
        implements KeyListener
        //static final String newline = System.getProperty ("line.separator");
        JButton button;
        private JFrame frame = new JFrame ();
            //Sets location, size, and visiblity to the frame where the JOptionPane
            //will be placed
            frame.setLocation (600, 600);
            frame.setSize (1, 1);
            frame.setVisible (false);
        JButton button1;
        public int xCord = 2;
        public int yCord = 2;
        public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
        //    button = new JButton ("TEST");
        //    ButtonHandler handler = new ButtonHandler ();
         //   button.addActionListener (handler);
          //  one.add (button);
            g.setColor (Color.white);
            g.fillRect (500, 100, 200, 300);
            g.setColor (Color.black);
            g.drawRect (500, 100, 200, 300);
            g.setFont (new Font ("Verdana", Font.BOLD, 25));
            g.setColor (Color.black);
            g.drawString ("LEVEL ONE", 525, 80);
            //ROW ONE
            counter = -80;
            counter2 = 200;
            for (int a = 1 ; a <= 7 ; ++a)
                if (xCord < a && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
                if (xCord > a - 1 && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
                counter += 40;
                counter2 += 40;
            int y = 100;
            int x = 100;
            for (int a = 0 ; a < 20 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                y += 40;
                if (a == 9)
                    x += 320;
                    y = 100;
            x = 140;
            y = 100;
            for (int a = 0 ; a < 14 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                x += 40;
                if (a == 6)
                    x = 140;
                    y += 360;
            g.setColor (Color.black);
            g.drawRect (100, 100, 360, 400);
            ImageIcon[] images = new ImageIcon [4];
            images [0] = new ImageIcon ("arrow_left.gif");
            images [1] = new ImageIcon ("arrow_up.gif");
            images [2] = new ImageIcon ("arrow_down.gif");
            images [3] = new ImageIcon ("arrow_right.gif");
            int direction = -1;
            //frame.setVisible (true);
            // direction = JOptionPane.showOptionDialog (frame, "Choose Your //\Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
            //         JOptionPane.QUESTION_MESSAGE,
            //         null,
            //         images,
            //         images [3]);
            // if (direction == 0)
            //     if (xCord - 1 > 0)
            //         xCord -= 1;
            //         xLoc += 40;
            // if (direction == 1)
            //     if (yCord - 1 > 0)
            //         yCord -= 1;
            //         yLoc += 40;
            // if (direction == 2)
            //     if (yCord + 1 < 9)
            //         yCord += 1;
            //         yLoc -= 40;
            // if (direction == 3)
            //     if (xCord + 1 < 13)
            //         xCord += 1;
            //         xLoc -= 40;
            one.addKeyListener (this);
            // one.add (button1);
            if (xCord == 1)
                LevelOne (g, one, gbc);
        /** Handle the key typed event from the text field. */
        public void keyTyped (KeyEvent e)
        /** Handle the key pressed event from the text field. */
        public void keyPressed (KeyEvent e)
            if (e.getSource () == "Up")
                JOptionPane.showMessageDialog (null, "Hi", "Hi", 0, null);
        /** Handle the key released event from the text field. */
        public void keyReleased (KeyEvent e)
            // displayInfo (e, "KEY RELEASED: ");
    }

  • Why "parent is null"?

    Hi guys,
    I'm developing a simple Applet application with JDK 1.3.1.
    All of codes are the following,
    DemoApplet.java
    public class DemoApplet extends Applet {
      private static final long serialVersionUID = -371112038768840393;
      public DemoApplet() {
        BorderLayout gridLayout = new BorderLayout();
        setLayout(gridLayout);
        add(new DemoPanel(), BorderLayout.CENTER);
      public void init() {
    }DemoPanel.java
    public class DemoPanel extends Panel {
      private static final long serialVersionUID = -5992125460349250223;
      private DemoPopupMenu popupMenu = new DemoPopupMenu();
      public DemoPanel() {
        addMouseListener(mouseAdapter);
      private MouseAdapter mouseAdapter = new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
          if (SwingUtilities.isRightMouseButton(e)) {
            popupMenu
                .show((DemoPanel) e.getComponent(), e.getX(), e.getY());
    }DemoPopupMenu .java
    public class DemoPopupMenu extends PopupMenu {
      private static final long serialVersionUID = -7751149413579159572;
      private Menu menu = new Menu("PopuMenu");
      public DemoPopupMenu() {
        add(menu);
    }When I run DemoApplet with appletviewer, an exception was thrown:
    Exception occurred during event dispatching:
    java.lang.NullPointerException: parent is null
      at java.awt.PopupMenu.show(PopupMenu.java:102)
      at test.demo.DemoPanel$1.mouseClicked(DemoPanel.java:23)
      at java.awt.Component.processMouseEvent(Component.java:3713)
      at java.awt.Component.processEvent(Component.java:3539)
      at java.awt.Container.processEvent(Container.java:1159)
      at java.awt.Component.dispatchEventImpl(Component.java:2588)
      at java.awt.Container.dispatchEventImpl(Container.java:1208)
      at java.awt.Component.dispatchEvent(Component.java:2492)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:334)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:126)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:93)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:88)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:80) But if I changed all of PopupMenu/Menu to JPopupMenu/JMenu, all was OK.
    Although the old AWT codes aren't recommended, I don't think the application is wrong.
    I'm puzzled by the matter.
    I wish some friend would explain the matter.
    Thanks in advance!
    a cup of Java, cheers!
    Sha Jiang
    Edited by: jiangshachina on Oct 29, 2007 4:44 PM

    Oh, I get it.
    Thanks for the reply.
    Rewards a Duck star :-D
    You never added the popupMenu to anything. Therefore, it has no parent and is not part of any component hierarchy.With the error output, I known the DemoPopupMenu need a "parent" component.
    But I simple think DemoPanel is the parent for DemoPopupMenu,
    because DemoPopupMenu is included by DemoPanel (so foolish!)
    Also, you should not use isRightMouseButton() for handling popup actions.
    There is a method called isPopupTrigger() in the MouseEvent class.
    Call this in the mousePressed() and mouseReleased() methods of your MouseListener (instead of mouseClicked).I know the method isPopupTrigger().
    In fact, at the beginning, I used isPopupTrigger(), but it didn't work.
    Whether I right-click or left-click, both of the values of isPopupTrigger() are "false".
    Then I have to redirect to isRightMouseButton() :-(

  • ToggleButton menu element needed!

    hi everyone!
    I am not a Swing guru but I need in my JMenu a ToggleButton element (with two states) using the Java 6 Platform. Paging through the javadoc shows you that JMenuItem, JToggleButton and JButton derive from AbstractButton. As it seems to me is that the JMenuItem is the menu element implementation of JButton. What I need is a menu element implementation of JToggleButton, which allows you to place such en element inside a JMenu and use it as it were a JToggleButton (which means that you can't subclass JToggleButton to create such an element).Well here is an idea how to start:
    import java.awt.Component;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseEvent;
    import javax.accessibility.Accessible;
    import javax.accessibility.AccessibleContext;
    import javax.swing.AbstractButton;
    import javax.swing.MenuElement;
    import javax.swing.MenuSelectionManager;
    public class JMenuToggleItem extends AbstractButton implements Accessible, MenuElement{
        public JMenuToggleItem() {
         *Processes a mouse event. event is a MouseEvent  with source being the receiving
         * element's component. path is the path of the receiving element in the menu
         * hierarchy including the receiving element itself. manager is the
         * MenuSelectionManager  for the menu hierarchy. This method should process the
         * MouseEvent and change the menu selection if necessary by using MenuSelectionManager's
         * API Note: you do not have to forward the event to sub-components.
         * This is done automatically by the MenuSelectionManager.
         * @param mouseEvent
         * @param menuElements
         * @param menuSelectionManager
        public void processMouseEvent(MouseEvent mouseEvent,
                                      MenuElement[] menuElements,
                                      MenuSelectionManager menuSelectionManager) {
         *Process a key event.
         * @param keyEvent
         * @param menuElements
         * @param menuSelectionManager
        public void processKeyEvent(KeyEvent keyEvent, MenuElement[] menuElements,
                                    MenuSelectionManager menuSelectionManager) {
         *Call by the MenuSelectionManager when the MenuElement is added or remove from the
         * menu selection.
         * @param b
        public void menuSelectionChanged(boolean b) {
         *This method should return an array containing the sub-elements for the receiving
         * menu element
         * @return
        public MenuElement[] getSubElements() {
            return new MenuElement[0];
         * This method should return the java.awt.Component used to paint the receiving element.
         * @return Component
        public Component getComponent() {
            return null;
         *Returns the AccessibleContext associated with this object. In most cases,
         * the return value should not be null if the object implements interface Accessible.
         * If a component developer creates a subclass of an object that implements Accessible,
         * and that subclass is not Accessible, the developer should override the
         * getAccessibleContext method to return null.
         * @return
        public AccessibleContext getAccessibleContext() {
            return null;
    }Any ideas how to implement this or has it been already implemented somewhere else?
    Any help is will be very appreciated!
    Thank you!

    Won't do the job buddy! I need the ToggleButton functionality like a media players toggle button play/pause. Look at the YouTube videoplayer as an example!

  • How to fine tune your GUI?

    Hello!
    I am pretty new at Java and i have search for information about how to fine tune your GUI but have not found anything.
    Last time when i wrote a program with a GUI I manually placed out all the widgets. This time I was thinking to give the layotmanager another go. But when I do I cant seem to easly place things exactly where I whant.
    For instance in this code, all my buttons are to the left in the boarder layout north part.
    I whant to learn:
    How do I move all the buttons to the right, little further down, etcetera to my specifications
    Please if someone could provide me a link to a website, tip on what I need to search for. So I can learn how to do this when you mix diffrent layoutmanager in one GUI.
    Example of my code:
    //Import java library
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class View_Inlupp2 {
         //*****GUI Components
         //Menu File Items
         private JMenuItem New = new JMenuItem("New");
         private JMenuItem Open = new JMenuItem("Open");
         private JMenuItem Save = new JMenuItem("Save");
         private JMenuItem Save_As = new JMenuItem("Save as");
         //Menu Operations Items
         private JMenuItem Find_Route = new JMenuItem("Find Route");
         private JMenuItem Show_Connections = new JMenuItem("Show Connections");
         private JMenuItem New_Place = new JMenuItem("New Place");
         private JMenuItem New_Connection = new JMenuItem("New Connection");
         private JMenuItem Change_Connection = new JMenuItem("Change Connection");
         //Top field
         private JButton Find_RouteBtn = new JButton("Find Route");
         private JButton Show_ConnectionsBtn = new JButton("Show Connections");
         private JButton New_PlaceBtn = new JButton("New Place");
         private JButton New_ConnectionBtn = new JButton("New Connection");
         private JButton Change_ConnectionBtn = new JButton("Change Connection");
         //Left side
         //Center
         public View_Inlupp2() {
              //Create and show the GUI.
              createAndShowGUI();
         //**********GUI Structure
         private JPanel createContentPane() {
              //Create the JPanel where we will put everything on
              JPanel totalGUI = new JPanel();
              //Set totalGui to have a BorderLayout with a horizontal
              //gap of 10 and a vertical gap of 10 between each widget
              totalGUI.setLayout(new BorderLayout(10, 10));
              //*****Top Field
              //Create a holder for the buttons with a BoxLayout.LINE_AXIS
              JPanel top = new JPanel();
              top.setLayout(new BoxLayout(top, BoxLayout.LINE_AXIS));
              top.add(Find_RouteBtn);
              top.add(Show_ConnectionsBtn);
              top.add(New_PlaceBtn);
              top.add(New_ConnectionBtn);
              top.add(Change_ConnectionBtn);
              //*****Put our GUI together and add all the widgets to our totalGUI
              totalGUI.add(top, BorderLayout.NORTH);
              totalGUI.setOpaque(true);
              return totalGUI;
         private JMenuBar createMenuBar() {
              //Create a menuBar
              JMenuBar menuBar = new JMenuBar();
              //Create menus
              JMenu File = new JMenu("File");
              JMenu Operations = new JMenu("Operations");
              //Add menus to menuBar
              menuBar.add(File);
              menuBar.add(Operations);
              //Add menuItems to the File menu
              File.add(New);
              File.add(Open);
              File.add(Save);
              File.add(Save_As);
              //Add menuItems to the Operations menu
              Operations.add(Find_Route);
              Operations.add(Show_Connections);
              Operations.add(New_Place);
              Operations.add(New_Connection);
              Operations.add(Change_Connection);
              return menuBar;
         //**********Create the window frame
         //Create the frame and add the created content pane.
         private void createAndShowGUI() {
              JFrame.setDefaultLookAndFeelDecorated(true); //The program look the same on Windows, Mac and Linux
              JFrame frame = new JFrame("Inlupp2");
              //Set the ContentPane, menuBar, and the settings for our window
              frame.setContentPane(createContentPane());
              frame.setJMenuBar(createMenuBar());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(1024, 640);
              //frame.setResizable(false);
              frame.setVisible(true);
         //**********Interaction
         //Add the ActionListener passed by the Controller to each of the buttons
         public void buttonActionListeners(ActionListener al) {
         }//End buttonActionListener
    }//End class

    First of all, learn and use proper Java naming conventions. All text books, tutorial and code examples on the forums use these naming conventions. So don't make up your own. Variable names should NOT start with an upper case character.
    By default a JPanel uses a FlowLayout. Read the API to learn how to change the default left alignment to center or right.
    If you want extra space around a panel you can use an EmptyBorder.
    Both of these topics are covered in the Swing tutorial and you've been given the link to the tutorial in the past.
    Also, the code you posted is not executable so we can't see the problems you attempt to descripe.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://sscce.org], that demonstrates the incorrect behaviour.

  • Disabled JMenuItem doesn show animated gif

    Hi there
    I would like to have a popup menu with actions that are enabled after they have finished with some background task taking some time. Basically this works fine for the enabling action on a shown popup. However, adding an animated gif as the icon or disabled icon does not show it in disabled state. In enabled state it works perfect. Please have a try with the sample code. You should see the disabled item for 2 secs and the icon is not showing up. After being enabled, it does. Invoking the menu again shows the animated gif in its last state left, but not moving any more.
    I guess, repaints are not done appropriately in disabled state... Any ideas how to solve that would be highly appreciated :-)
    Actually I used the icon at http://mentalized.net/activity-indicators/indicators/pascal_germroth/indicator.white.gif
    Cheers
    Daniel
    public class Main
      public static void main(String[] args)
        final JFrame frame = new JFrame();
        frame.addMouseListener(new MouseAdapter()
          public void mousePressed(final MouseEvent e)
            final JPopupMenu popup = new JPopupMenu();
            popup.add(new JMenuItem("Open..."));
            popup.add(new JMenuItem("Close"));
            final JMenuItem action = new JMenuItem("Long loading until enabled");
            action.setIcon(new ImageIcon("C:/spinner.gif"));
            action.setDisabledIcon(new ImageIcon("C:/spinner.gif"));
            popup.add(action).setEnabled(false);
            popup.show(e.getComponent(), e.getX(), e.getY());
            SwingUtilities.invokeLater(new Runnable()
              public void run()
                try
                  Thread.sleep(2000);
                  action.setEnabled(true);
                catch (InterruptedException e1)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }Edited by: daniel.frey on Apr 22, 2009 7:50 AM

    The problem is that you are causing the EDT to sleep, which means the GUI can't repaint itself. Read the section from the Swing tutorial on Concurrency to understand what is happening.

  • 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

Maybe you are looking for

  • After transfer to new server, doesn't work

    Hello iTunes U Administrators, A short description about my iTunes U experience - none. I am a new hire at my academic institution, and it so happens that the folks with the most experience with setting up iTunes U have just left for vacation. We jus

  • HT201335 Is there a way to use airplay mirror on iPhone 4??

    Is there a way to use airplay mirror on iPhone 4 via apple TV??

  • Mass-deletion of PR-items

    Hello gurus, I would like to delete up to 5000 purchase request items (i.e. set the deletion flag, EBAN-LOEKZ). Unfortunatelly this is not possible using MEMASSRQ. In another forum I found a message saying the deletion cannot be set using MEMASSRQ be

  • Event ID 6 cmdlet failed

    On my Exchange 2010 server with SP1 (cas/hub/mbx) every minute in the Eventlog > Custom Views > Administrative Events (not in application/system) > I get 3 event id 6 errors Event ID 6 cmdlet failed. Cmdlet Get-MailboxDatabase, parameters {Server=SER

  • Table for maint. Order & Service

    Hi All, I have created one maint. order with external service. In which table i could find the service against the order. I have checked ESLL but there is no Order link. regards sunil