JMenu hidden unde JPanel

Hi,
I write same simple application, and I have problem with a JMenu. When I make simple JMenu, and add it to this application, menu this will be hiden under JPanel and other controls...
Here id code:
Hi,
I write same simple application, and I have problem with a JMenu. When I make simple JMenu, and add it to this application, menu this will be hiden under JPanel and other controls...
Here id code:
package pl.staniszczak.JFakturka.GUI;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Panel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import pl.staniszczak.JFakturka.GUI.Actions.DrukujFaktureAction;
import pl.staniszczak.JFakturka.GUI.Models.TowaryATModel;
* @author Administrator
public class MainFrame extends JFrame {
     private JTextField jtfNrFaktury;
     private JFormattedTextField jftfDataSprzedazy;
     private JFormattedTextField jftfDataFaktury;
     private JComboBox jcbPlatnosc;
     private JSpinner jsTerminPlatnosci;
     private JTextField jtfUwagi;
     private JTable jtTowary;
     private JButton jbDodajTowar;
     private JButton jbUsunTowar;
     public MainFrame() {
          setTitle("JFakturka 1.0");
          setResizable(false);
          setSize(450,400);
       * Menus
        JMenu menuFaktura = new JMenu("Faktura");
        JMenuItem drukuj = menuFaktura.add(new DrukujFaktureAction("Drukuj"));
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        menuBar.add(menuFaktura);
         * Układ komponent�w
          //gł�wny layout
          GridLayout gridLayout = new GridLayout(2,1);
          getContentPane().setLayout(gridLayout);
          //layout na kompionenty tekstowe
          Panel pnlText = new Panel();
          GridBagLayout gblLayout = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.WEST;
          pnlText.setLayout(gblLayout);
          add(pnlText);
        * Komponenty
          //Numer faktury
        JLabel jlblNrFaktury = new JLabel("Numer Faktury");
        buildConstraints(constraints, 0,0,1,1,100,100);
        gblLayout.setConstraints(jlblNrFaktury, constraints);
        pnlText.add(jlblNrFaktury);
        jtfNrFaktury = new JTextField(25);
        buildConstraints(constraints, 1,0,3,1,100,100);
        gblLayout.setConstraints(jtfNrFaktury, constraints);
        pnlText.add(jtfNrFaktury);
        //Data sprzedaży
        JLabel jlblDataSprzedazy = new JLabel("Data sprzedaży");
        buildConstraints(constraints, 0,2,1,1,100,100);
        gblLayout.setConstraints(jlblDataSprzedazy, constraints);
        pnlText.add(jlblDataSprzedazy);
        jftfDataSprzedazy = new JFormattedTextField();
        buildConstraints(constraints, 1,2,1,1,100,100);
        gblLayout.setConstraints(jftfDataSprzedazy, constraints);
        pnlText.add(jftfDataSprzedazy);
        //Data faktury
        JLabel jlblDataFaktury = new JLabel("Data faktury");
        buildConstraints(constraints, 2,2,1,1,100,100);
        gblLayout.setConstraints(jlblDataFaktury, constraints);
        pnlText.add(jlblDataFaktury);
        jftfDataFaktury = new JFormattedTextField();
        buildConstraints(constraints, 3,2,1,1,100,100);
        gblLayout.setConstraints(jftfDataFaktury, constraints);
        pnlText.add(jftfDataFaktury);
        //Płatność
        JLabel jlblPlatnosc = new JLabel("Płatność");
        buildConstraints(constraints, 0,3,1,1,100,100);
        gblLayout.setConstraints(jlblPlatnosc, constraints);
        pnlText.add(jlblPlatnosc);
        jcbPlatnosc = new JComboBox(new String[]{"Got�wka", "Przelew", "Inna"});
        buildConstraints(constraints, 1,3,1,1,100,100);
        gblLayout.setConstraints(jcbPlatnosc, constraints);
        pnlText.add(jcbPlatnosc);
        //Termin płatności
        JLabel jlblTerminPlatnosc = new JLabel("Termin");
        buildConstraints(constraints, 2,3,1,1,100,100);
        gblLayout.setConstraints(jlblTerminPlatnosc, constraints);
        pnlText.add(jlblTerminPlatnosc);
        jsTerminPlatnosci = new JSpinner();
        buildConstraints(constraints, 3,3,1,1,100,100);
        gblLayout.setConstraints(jsTerminPlatnosci, constraints);
        pnlText.add(jsTerminPlatnosci);
        //Uwagi
        JLabel jlblUwagi = new JLabel("Uwagi");
        buildConstraints(constraints, 0,4,1,1,100,100);
        gblLayout.setConstraints(jlblUwagi, constraints);
        pnlText.add(jlblUwagi);
        jtfUwagi = new JTextField(25);
        buildConstraints(constraints, 1,4,3,1,100,100);
        gblLayout.setConstraints(jtfUwagi, constraints);
        pnlText.add(jtfUwagi);
        //Dodaj towar
          jbDodajTowar = new JButton("Dodaj towar");
        buildConstraints(constraints, 0,5,4,1,100,100);
        gblLayout.setConstraints(jbDodajTowar, constraints);
        pnlText.add(jbDodajTowar);
        //Usuń towar
          jbUsunTowar = new JButton("Usun towar");
        buildConstraints(constraints, 1,5,4,1,100,100);
        gblLayout.setConstraints(jbUsunTowar, constraints);
        pnlText.add(jbUsunTowar);
        //Towary
        TowaryATModel towaryModel = new TowaryATModel();
        jtTowary = new JTable(towaryModel);
        add(new JScrollPane(jtTowary));
     public void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
          gbc.gridx = gx;
          gbc.gridy = gy;
          gbc.gridwidth = gw;
          gbc.gridheight = gh;
          gbc.weightx = wx;
          gbc.weighty = wy;
}

It's my bug - I use Panel from AWT. When I replace it by JPanel, it's start work:-)

Similar Messages

  • Switching jpanels implemented in different classes

    Hi,
    I'm quite new to swing applications (not to java) and I run into a problem I couldn't solve.
    I got a frame and in that frame a jMenu and a jPanel.
    I want to create an application where you have to log in, so my first jPanel represents the login (LogInPanel). After a succesful login I want to replace the LogInPanel with an other (LoggedInPanel). This class doesn't belong to my main class and is implemented separatly.
    My questions are:
    1.)is it possible create a gui like that or is there an other, better way, beside doing everything in one class?
    2.)how can I change from the LogInPanel to the LoggendInPannel after I called the jButtonLogin_actionPerformed(ActionEvent e) from the LogInPanel
    3.)I also want to change the state of some values in my jMenu after successful login, but I don't know how to get access to them from my LoggedInPannel class.
    Thanks for any help
    Jens

    I don't really understand your problem, but I've had headaches with managing a GUI before (as many programmers have, I'm sure).
    My best advice, if the scheme your using to build and manage a GUI is too confusing for you, the programmer, to easily understand/manage, change the scheme. Even if this means recoding a good deal of your program (though, hopefully, you've kept the GUI as seperate from your functional code as possible) it should be worth it.
    Perhaps a clearer explination of your problem would help better illustrate your problem?
    -Rejun

  • JMenu is not shown completely

    Hello.
    I've created an application with a JMenu. Now I have the problem that it is not shown completely. It's just shown the beginning until there's a JPanel and then the JPanel covers the JMenu. How can I change the program that the JMenu covers the JPanel and not reverse?
    Please help.

    Without a code sample it's difficult to be precise. However it sounds as if you may be using a borderlayout and placing the JPanel in the same area as the JMenu. For example you may have code like:container.add(menu,BorderLayout.NORTH);
    container.add(panel,BorderLayout.NORTH);

  • JPanel getting out of Frame.

    I have a JPanel inserted into a JTabbedPane which is part of a JSplitPane that consist of two JTabbedPanes. Everything is displaying alright until I start to slide the splitter of the JSplitPane. When I try to minimize the portion of the JSplitPane with the JPanel inserted, instead of being hidden, the JPanel slide out of the JInternalFrame that it is resided in. Resulting a JInternalFrame with a JPanel protruding on it's side.
    I completely do not have any idea what's going on. Could it be a layering problem? Could anyone provides any clues or best remedy to my problem. Thanks in advance.
    Thank you.

    Thanks jdcanki,
    When I was preparing to post the code. I found one very classic mistake that I had made.
    Probably you may already had guessed correctly already, there are some heavy-weighted component in the JPanel that I insert into the JInternalFrame, thus causing this overlapping of display.
    I had corrected the error and confirmed that this is the main cause. Thanks you for making me to go thru my code again.
    Thank you.

  • JMenu disappearance - all or nothing?

    Hello all,
    I'm trying to make a JMenu that pops up and remains up until you click outside the menu. The reason I'm doing this is because I added a JPanel with a bunch of components to the JMenu (rather than a JMenuItem), and I want it to remain open so the user can enter information, etc.
    Now, I've overloaded the JMenu class, like so:
    private class HoverMenu extends JMenu implements ActionListener
              JPanel mypanel;
              HoverMenu myself;
              CoolButton exitBut;
              JPanel masterPanel;
              public HoverMenu(String str, String loadFrom, JPanel newpanel, int width, int height)
                   //super(str, loadFrom, width, height);
                   super(str);
                   myself = this;
                   mypanel = newpanel;
                   //setSelectColor(new Color(0,0,255,50));
                   exitBut = new CoolButton(" E X I T ", codebase.toString() + "BrushMetal.JPG");
                   masterPanel = new JPanel();
                   masterPanel.setLayout(new BorderLayout());
                   masterPanel.add(mypanel, BorderLayout.CENTER);
                   masterPanel.add(exitBut, BorderLayout.SOUTH);
                   this.add(masterPanel);
                   exitBut.addActionListener(this);
              public void actionPerformed(ActionEvent z) {
                   if(z.getSource() == exitBut) {
                        setPopupMenuVisible(false);
                        repaint();
              protected void processMouseEvent(MouseEvent e)
                   System.out.println("/////////////");
                   System.out.println(e.paramString());
                   //super.processMouseEvent(e);
                   System.out.println("CAME OUT ALIVE!!!");
                   if(e.getID() == MouseEvent.MOUSE_CLICKED) {
                        setPopupMenuVisible(true);
                        /*System.out.println("Click...");
                        Rectangle mybounds = masterPanel.getBounds();
                        int x = e.getX();
                        int y = e.getY();
                        if(!mybounds.contains(new Point(x,y))) {
                             System.out.println("Closing...");
                             super.processMouseEvent(e);          
                        //setPopupMenuVisible(true);*/                              
                   //else {     
                   //     System.out.println("Business as usual...");
                   repaint();
              protected void processEvent(AWTEvent e) {
                   super.processEvent(e);
                   System.out.println("EVENT!!!--> " + e.paramString());
         }Now if I put super.processMouseEvent(e) back in and comment out setPopupMenuVisible(true), the menu will disappear if you click anywhere, on or off the menu. I cannot for the life of me figure out what event or whatever is being sent to what to make it disappear. If anybody has any clue what on earth is going on, I would be eternally grateful.

    When you import an iOS project into the Mac GarageBand all tracks are selected.  As a result muting or soloing any track causes all of them to be muted or soloed.  Select a single track and this won't be a problem.  If you have difficulty selecting a single track just add a new track and it will be the only one selected.

  • Menu and Thread.sleep(5000) or Thread.currentThread.sleep(5000)

    Hi,
    I am using JMenu and switchable JPanels.
    When I click on a MenuItem the follownig code should starts
        cards.add(listenPanel,  "listenPanel");
        cardLayout.show(cards, "listenPanel");
        try{
          Thread.sleep(5000); //in ms
          PlayMP3Thread sound = new PlayMP3Thread("sound/ping.mp3");
        } catch(Exception e) {
          e.printStackTrace();
        }It seems to be what I want to reach, but it does not work the way I want it to.
    I would like the Panel to show right away, then wait 5s and then play the sound.
    BUT what it does is freez the unfolded menu for 5s, then plays the sound and after that it shows the new Plane.
    Can you tell me why this is??

    This might be what you want
    package tjacobs.thread;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Semaphore;
    import tjacobs.ui.Eyes;
    import tjacobs.ui.util.WindowUtilities;
    public class ThreadForMultipleAnytimeRuns extends Thread {
         private Runnable mRunnable;
         private Semaphore mSemaphore;
         public ThreadForMultipleAnytimeRuns(Runnable arg0) {
              super();
              init(arg0);
         private void init(Runnable r) {
              mRunnable = r;
              mSemaphore = new Semaphore(0);
              setDaemon(true);
         public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
              super(arg1);
              init(arg0);
         public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
              super(arg0, arg2);
              init(arg1);
         public void run () {
              try {
                   while (!isInterrupted()) {
                        mSemaphore.acquire();
                        mRunnable.run();
              catch (InterruptedException ex) {}
         public void runAgain() {
              mSemaphore.release();
         public void runAgain(int numTimes) {
              mSemaphore.release(numTimes);
         public void stopThread() {
              interrupt();
         public int getSemaphoreCount() {
              return mSemaphore.availablePermits();
         public Runnable getRunnable() {
              return mRunnable;
         //The setRunnable method is simply not safe, and
         //trying to make it safe is going to effect performance
         //Plus I can't really see a gain in being able to set
         //The runnable on one of these threads. Just create
         //a new one!
         public synchronized void setRunnable(Runnable r) {
              if (getSemaphoreCount() > 0) {
                   try {
                        wait();
                   catch (InterruptedException ex) {
                        return;
              mRunnable = r;
         public static void main(String[] args) {
              final Eyes eyes = new Eyes(true);
              //eyes.addMouseMotionListener(eyes);
              Runnable r = new Runnable() {
                   public void run() {
                        eyes.blink();
                        try {
                             Thread.sleep(100);
                        catch(InterruptedException ex) {}
              final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
              ar.start();
              eyes.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        ar.runAgain();
              eyes.setPreferredSize(new Dimension(60,20));
              WindowUtilities.visualize(eyes);
    //          JFrame jf = new JFrame();
    //          jf.add(eyes);
    //          jf.pack();
    //          jf.setLocation(100,100);
    //          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          jf.setVisible(true);
    }

  • Making elements dimensions relative to other elements

    Attached is a picture of, roughly, what I want my app to look like. I did do it in paint, but I tried to make it look as nice as I could for you all. The red line is for reference only; it won't be in the app itself. Basically, the lower areas should be fully expanded vertically from the bottom of the app to the bottom of the {color:#0000ff}upper area (which remains unchanged most of the time, but the dimensions of that area never change) {color}and horizontally from the [left/right] edge of the app to the red line and the user should be able to move that red line.
    So far I have:
    {color:#0000ff}
    {color}JFrame
        JMenu(Bar?)
        JPanel (Upper Area)
    ...lost...
        JPanel (lower left)
            scroll bars
        JPanel (lower right)
            scroll barsI am totally new to this swing stuff so feel free to take me by the hand and slap me around with it if I'm too far off. Thank you.
    {color}
    Edited by: tenmiles on Jan 27, 2009 8:15 PM
    Edited by: tenmiles on Jan 27, 2009 8:45 PM
    Actually attached the picture this time.... http://xs135.xs.to/xs135/09052/appgui724.jpg

    tenmiles wrote:
    Thanks to both of you. I had played around with jSplitPane, but my IDE made both sides buttons by default and didn't really make it clear how to customize it further.If you're serious about learning, drop the visual designer like a hot potato. It can only hamper, not help, your learning.
    The visual designer can be a productive tool in the hands of someone who has already learned Swing coding.
    I also really like that link as it helped explain layouts beyond "don't try this at home, kids". Much appreciated.So click arounf a bit, you would have found [How to Use Split Panes|http://java.sun.com/docs/books/tutorial/uiswing/components/splitpane.html]
    db

  • Whiteboard TEXT

    I developed a whiteboard . To add minimum features to it I have come up on an idea of having a text tool . The tool should be in such a way that the user can type his text onto the canvas directly without disturbing its behind graphics . Is there a solution for this . I tried adding a JTextPane to a JPanel and hidden the JPanel so that the textcomponent is also hidden . when the user selects appropriate button the component becomes active . Now I made both the components transparent so that the graphics beneath it will be shown . I could'nt succeed in this . The panel component is not becoming transparent . It would be greatfull If I can have some help on the following information .

    hi,
    well, let me see , what you are trying to do, you are tring to create a custom white borad, well , let me suggest something, draw of the panel and repaint it, you can overload the paint and repaint methiods alse you can use a bitmap for faster drawing, well hope that answers your questions ok . you can also blit the bitmaps,
    query me back if you did'nt get that,
    myraid_77

  • Stop avi sound

    Hi
    I'm a student and i'm trying to building a program that play's some *.avi files.
    I've got a class named PLAY_MOVIE.
    This class has 2 methods:
    public Component PLAY_MOVIE_avi()
    public void setVolume(String volume)
    The constructor of this class initiates a String that contains the name of the *.avi file i want to play.
    The PLAY_MOVIE_avi() code is this, and it's working well:
    package xpto;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.String;
    import java.net.*;
    import java.net.MalformedURLException;
    import java.io.IOException;
    import java.util.Properties;
    import javax.media.*;
    import javax.swing.JOptionPane;
    import javax.media.protocol.*;
    import java.io.*;
    import javax.swing.*;
      public Component PLAY_MOVIE_avi()
        Component VC=null;
        try
          Player player;
          File MovieFile = new File(aux);
          player = Manager.createRealizedPlayer(MovieFile.toURL());
          VC = player.getVisualComponent();
          player.start();
        catch (Exception e)
          JOptionPane.showMessageDialog(null,"Inappropriate AVI data was encountered. Verify MOVIE files. The program will now
    close.");
          System.exit(0);
        return VC;
    The setVolume(String volume) function, is to regulate the volume of the playing avi file, through the String volume.
    My main goal is to set the volume to 0, cause when i use this class, a music is beeing played, so the music from the avi isn't desired.
    I use this class in another class, named VisualCT, which is responsible for the construction of GUI, etc.
    Next is a part of the VisualCT code:
    package xpto;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.sound.midi.*;
    import java.io.*;
    public class VisualCT extends JFrame implements ActionListener
      private Container c;
      private JMenuBar MB;
      private JMenu M1;
      private JPanel P;
      private JPanel P1;
      private JPanel P2;
        //PLAY_MUSIC m= new PLAY_MUSIC("MUSIC/Win.mid");
        PLAY_MUSIC m= new PLAY_MUSIC("MUSIC/Debriefing.mp3");
        m.PLAY_MUSIC_mp3();
        P1=new JPanel();
        P1.add(w);                       // w is an ImageIcon
        PLAY_MOVIE n1= new PLAY_MOVIE("MOVIES/camelrace-avi.avi");
        PLAY_MOVIE n2= new PLAY_MOVIE("MOVIES/SMB_AVI3_Export_lo.avi");
        P2=new JPanel();
        P2.add(n1.PLAY_MOVIE_avi());
        P2.add(n2.PLAY_MOVIE_avi());
        c.add(P1, BorderLayout.CENTER);
        c.add(P2, BorderLayout.SOUTH);
      public void actionPerformed(ActionEvent e)
        if(e.getSource() == MI1)
          c.remove(P1);
          c.remove(P2);
          //m.stopMusic();
          MI2.setEnabled(false);
          c.repaint();
        if(e.getSource() == MI11)
          System.exit(0);
    public static void main(String[] args)
       VisualCT VCT = new VisualCT();
    My idea is, when i create the n1 and n2 movies, next i want to call the n1.setVolume("0") and n2.setVolume("0") methods, to
    stop the sound.
    The problem is that i don't know how to do this.
    Another problem i have, is very similar to the first:
    I also have a PLAY_MUSIC class, which is able to play mp3 and midi files.
    For example, when i click a MenuItem i have the ActionListener interface ready to catch the event, and in this situation i
    want to stop the music, by calling m.stopMusic();
    How can i do this?
    If it's possible, i would like that someone would help me in these two situations.
    Sorry about my english. (I'm portuguese)
    Thanks.

    Please!!! I really need help in doing this.
    Give some ideas at least.

  • Event handling in JMenu in JPanel

    Hi,
    I'm writing a small register program GUI. I have a problem with ActionListener in JMenu. I wrote a JPanel which creates a JMenu and that works just fine. The problem is that id doesn't give any event signals. I have another class which impelemets ActionListener and it works fine with JButton (another panel for buttons), but not with JMenu.
    Below is the JPanel for JMenu and Application which implements the ActionListener. Do you see anything wrong? I really can't imagine why I cannot get the action signals. JPanel is defined in JFrame as it should be. Have you got any ideas?
    Regards,
    Marko
    class MenuPanel extends JPanel {
         protected JMenuBar menuBar;
         protected JMenu menu;
         protected JMenuItem loadRegister;
         protected JMenuItem saveRegister;
         protected JMenuItem information;
         protected JMenuItem quit;
         public MenuPanel(Application application) {
              menuBar = new JMenuBar();          
              menu = new JMenu("Tiedosto");     
              loadRegister = new JMenuItem("Lataa");
              loadRegister.addActionListener(application);
              saveRegister = new JMenuItem("Talleta");
              saveRegister.addActionListener(application);
              information = new JMenuItem("Tietoja");
              information.addActionListener(application);
              quit = new JMenuItem("Lopeta");                    quit.addActionListener(application);
              menu.add(loadRegister);
              menu.add(saveRegister);
              menu.addSeparator();
              menu.add(information);
              menu.add(quit);          
              menuBar.add(menu);
    class Application implements ActionListener {     
         // Define CardPanel
         private CardPanel cardPanel;
         // Define linked list for cards
         private CardList cardList = null;
         // Constructor. Initializes cardPanel and cardList
         public Application(CardPanel cardPanelRefrence) {
              cardPanel = cardPanelRefrence;
              cardList = new CardList();
         public void actionPerformed(ActionEvent action) {
              String actionPerformed = action.getActionCommand();
              if (actionPerformed.equals("Lataa")) {
                   load();          
              if (actionPerformed.equals("Talleta")) {
                   save();          
              if (actionPerformed.equals("Tietoja")) {
                   info();          
              if (actionPerformed.equals("Lopeta")) {
                   System.exit(0);
    // Continues with the methods...

    Well, I found the answer. Heh, quite easy one but it took a while before I found it..
    Just if you ever have similar problem. The problem was that in my JFrame I didn't create an object of class (Application) which implement s the ActionListener before using it as a reference in creating JPanel object. Quite confusing explanation, but here the code. This code was in my JFrame which was not included in this question.
    private Application application;
    private MenuPanel menuPanel;
    application = new Application(cardPanel, rightInfoPanel);
    menuPanel = new MenuPanel(application);
    These two were introduced other way round, so that variable "application" was null. What a problem in fact.. :)
    - Marko

  • Adding JMenu directly to a JPanel

    I am trying to add a JMenu directly to a JPanel, but it isn't functioning properly. It shows up, and looks the way I expect (with an arrow, like a sub-menu), but it doesn't display its popup menu when clicked. If I add the menu to a JMenuBar, and add that to the panel, it works, but the popup drops down below the button instead of to the right, and the arrow disappears. JMenuBar appears to be adding its own actions to every menu that it contains. JMenu is a descendant of AbstractButton, so I figured it would behave like one, but no luck.
    Any help would be appreciated. By the way, I have thought of using a JButton and a JPopupMenu together, but that is not a very elegant solution. I am looking for a way to make the JMenu behave as if it were in a JMenuBar.

    Hello Vijesh
    See the code below and tell me whether it is useful ?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class SwingA implements ActionListener
    JPopupMenu pop;
    JFrame frame;
    JPanel panel;
    JButton cmdPop;
         public static void main(String[] args)
         SwingA A=new SwingA();
         SwingA()
                   frame=new JFrame("PopUp");
                   frame.setSize(600,480);
                   frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
                   pop=new JPopupMenu();
                   cmdPop=new JButton("Click");
                   cmdPop.addActionListener(this);
    JMenuItem item = new JMenuItem("First");
    JMenuItem item1 = new JMenuItem("Second");
    pop.add(item);
    pop.add(item1);
                   panel=new JPanel();
                   panel.add(cmdPop);
                   frame.getContentPane().add(panel);
                   frame.setVisible(true);
         public void actionPerformed(ActionEvent source)
    pop.show(cmdPop, cmdPop.getWidth(), 0);
    kanad

  • JMenu (on JPanel)

    I have an application that needs a menu but I can't have it at the top where a normal JMenu should go, what can I do? I have used JMenus on JFrames before but was wondering/hoping there was a simliar way to use a JMenu directly on a JPanel of some sort (?).

    Add the JMenubar with its JMenus to the JPanel just like a normal component, but make sure you change the layout manager of the JMenubar to says GridLayout (or BoxLayout with Y_AXIS layout), so that it can appear vertical instead of the default horizontal produced by its default BoxLayout with X_AXIS layout
    ICE

  • I want to have JMenu on a Side bar(JPanel) with sub menu.

    I want to have the JMenu on the sidebar(which is a
    JPanel placed at WEST). This JMenu shall have the sub
    menu with it. I got the JMenu on the Sidebar but when
    i take mouse over(or click) the MenuItem it is
    displaying the sub Menu. I am attaching the my code.
    Can anyone please let me know why it is not displaying
    the sub menu and what should be added to my code to
    work?
    Thanks in Advance(see below for code)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class SideBarMenu extends JFrame {
         JMenuItem menuItem1,menuItem2;
         JMenu books, softwares, tools;
         JSeparator horizontal1, horizontal2,horizontal3;
         JPanel p1, p2;
          public static void main(String[] args) {
           SideBarMenu vAR =  new SideBarMenu();
         public SideBarMenu() {
              super("Side Bar");
              setSize(500,500);
              setLocation(150,100);
              setResizable(true);     
              Container content = getContentPane();
              p1 = new JPanel(new BorderLayout());
              p2 = new JPanel();
              p2.setLayout(new GridLayout(20,1));
              p2.setBorder(BorderFactory.createLineBorder(Color.black,1));
              books = new JMenu("Books");
              horizontal1 = new JSeparator( JSeparator.HORIZONTAL );
              softwares = new JMenu("Softwares");
              horizontal2 = new JSeparator( JSeparator.HORIZONTAL );
              tools = new JMenu("Tools");
                                    horizontal3 = new JSeparator( JSeparator.HORIZONTAL );
              //sub Menu for menu "books"     
              menuItem1 = new JMenuItem("Java");
              books.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              books.add(menuItem2);
              //sub Menu for menu "Softwares"          
              menuItem1 = new JMenuItem("Java");
              softwares.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              softwares.add(menuItem2);
              //sub Menu for menu "tools"          
              menuItem1 = new JMenuItem("Java");
              tools.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              tools.add(menuItem2);
              p2.add(books);
              p2.add(horizontal1);
              p2.add(softwares);
              p2.add(horizontal2);
              p2.add(tools);
              p2.add(horizontal3);
              p1.add(p2,BorderLayout.WEST );
              content.add(p1);
              setVisible(true);
    }

    Hi Ashwin,
    I saw the above code which is approaching my requirement... Thats cool man. Taking that as reference i modified it to make it what i want. The code i have modified and which is very closer to my requirement is attached below. I have set the Windows Look and Feel, because its easy to track my problems with it. The problems am having are:
    1) When the mouse is removed from the menu its submenu is not disappearing.
    2) When i take the mouse over the menu its making the name(Books/softwares/tools) of the menu invisible.
    3) When i take the mouse over the sub menu items they are not getting highlighted, which means they are not listening
    I hope u will solve these issues for me...
    Also make the menu items work ie., just make them print when i click submenus like "Clicked books->java" and "clicked softwares->.Net" so that i get an idea of events....
    Many Thanks .
    Here we go,
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JSeparator;
    import javax.swing.UIManager;
    public class SideBarMenu4 extends JFrame
        JMenuBar menuBar;
        JPopupMenu popup = new JPopupMenu();
        JMenuItem menuItem1, menuItem2;
        JMenu books, softwares, tools;
        JLabel mainMenu = new JLabel("Main Menu");
        JMenu subMenu;
        JSeparator horizontal1, horizontal2, horizontal3;
        JPanel p1, p2;
        public static void main(String[] args)
            SideBarMenu4 vAR = new SideBarMenu4();
        public SideBarMenu4()
            super("Side Bar");
            setSize(500, 500);
            setLocation(150, 100);
            setResizable(true);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            Container content = getContentPane();
            p1 = new JPanel(new BorderLayout());
                        try {
              //MetalLookAndFeel.setCurrentTheme(new MacMetricsTheme());
                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");            
            } catch(Exception e) {}
            p2 = new JPanel();
            p2.setLayout(new GridLayout(30, 1));
            p2.setBorder(BorderFactory.createLineBorder(Color.black, 1));
            books = new JMenu("Books");
            horizontal1 = new JSeparator(JSeparator.HORIZONTAL);
            softwares = new JMenu("Softwares");
            horizontal2 = new JSeparator(JSeparator.HORIZONTAL);
            tools = new JMenu("Tools");
            horizontal3 = new JSeparator(JSeparator.HORIZONTAL);
            // sub Menu for menu "books"
            menuItem1 = new JMenuItem("Java");
              popup.add(menuItem1);
            //books.add(menuItem1);
            menuItem2 = new JMenuItem(".Net");
              popup.add(menuItem2);
              popup.setPopupSize(100,50);
            menuBar = new JMenuBar();
            menuBar.setLayout(new GridLayout(0, 1, 5, 5));
            books.add(popup);
              books.setComponentPopupMenu(popup);
            books.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(books, 88, 0);
              softwares.add(popup);
              softwares.setComponentPopupMenu(popup);
            softwares.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(softwares, 88, 0);
              tools.add(popup);
              tools.setComponentPopupMenu(popup);
            tools.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(tools, 88, 0);
            // p2.add(menuBar);
            p2.add(books);
              p2.add(horizontal1);
              p2.add(softwares);
              p2.add(horizontal2);
              p2.add(tools);
              p2.add(horizontal3);
            p1.add(p2, BorderLayout.WEST);
            content.add(p1);
            setVisible(true);
    }

  • Printing multiple hidden JPanels using Book and Pageable

    I am trying to print a number (in some cases a large number) of JPanels that reside in a Vector; they are only visible one-at-a-time but need to be printed all together. When printing if I am viewing the first page the first page is printed. If viewing any other page nothing is printed at all. I believe that the latter issue is a result of the first page being blank and causing printing to halt when NO_SUCH_PAGE is returned to the print manager.
    After some searching I have found no reasonable way to manage this. Displaying each page before appending it to the Book will be cumbersome so I am looking for a way to take each JPanel out of the Vector and add it to the Book for printing.
    public static void print(Vector book) {
          bk = new Book();     
          PageFormat pf = new PageFormat();
          pf.setOrientation(PageFormat.LANDSCAPE);
          Paper sheet = pf.getPaper();
          sheet.setSize(paperWidth, paperHeight);
          sheet.setImageableArea(x, y, width, height);
          pf.setPaper(sheet);
          for (Iterator it = book.iterator(); it.hasNext();) {
             bk.append(new PrintPage((Preview)(it.next())), pf);
          print();
       protected static void print() {
          PrinterJob printJob = PrinterJob.getPrinterJob();     
          printJob.setPageable(bk);
          if (printJob.printDialog()) {
             try {
                printJob.print();
             } catch (PrinterException pe) {
                System.out.println("Error printing: " + pe);
       }Any help would be much appreciated. If you have any idea how this might be accomplished I would love to hear it.
    Thanks...

    An update...
    I have ferreted the issues down to a strange inconsistency in the Printable page class:
    public class PrintPage implements Printable {
       Component toBePrinted;
       public PrintPage(Component componentToBePrinted) {
          this.toBePrinted = componentToBePrinted;
    //         JFrame testFrame = new JFrame();
    //         testFrame.getContentPane().add(toBePrinted);
    //         toBePrinted.setVisible(true);
    //         toBePrinted.validate();
    //         testFrame.pack();
    //         testFrame.setVisible(true);
       public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
          if (pageIndex > 0) {
             return NO_SUCH_PAGE;
          } else {
             Graphics2D g2d = (Graphics2D) g;
    //         JFrame testFrame = new JFrame();
    //         testFrame.getContentPane().add(toBePrinted);
    //         toBePrinted.setVisible(true);
    //         toBePrinted.validate();
    //         testFrame.pack();
    //         testFrame.setVisible(true);
             g2d.translate(pageFormat.getImageableX(),  pageFormat.getImageableY());
             disableDoubleBuffering(toBePrinted);
             toBePrinted.setVisible(true);
             toBePrinted.validate();
             toBePrinted.paint(g2d);
             enableDoubleBuffering(toBePrinted);
             return PAGE_EXISTS;
       }(Fogive the commented lines, they are to illustrate the JFrame test described below)
    If I create a new JFrame in the constructor and add the JPanel / Component 'toBePrinted' to it I can see the contents perfectly fine. If I do the same in the print() method prior to printing there is only content for the first page and four other JFrames with no content. It seems that the JPanels are not being rendered in the print() method which is screwy since the constructor has no problems, the same scope, access, etc.
    Any ideas?

  • Hidden Jlabel(Layer )  must be shown on JPanel

    Hello World,
    I have been dynamically adding a JLabel which in mycase is a transparent layer
    to the ImagePanel and the imagePanel are added to the SeriesPanel(JPanel) which
    has 2 comp viewPanel(Jpanel) on which the series of ImagePanels are added and
    JscrollBar and the issue is the added Jabel is visible only on unscrolled region  of the
    panel and its not added to the ImagePanel  when  it is scrolled
    The hierarchy is
    1 SeriesPanel---> 1..* ImagePanel--->1..*JLableLayers
    note
    I tried validate.invalidate,revalidate,repaint but in vain
      Thanx in Advance

    Now only i noticed that line without punctuation :-) anyway
    y the code is here ..
    this method is called from paintComponent() of the seriesPanel.
    Panel -Widget
      this.add(view,BorderLayout.CENTER);
            this.add(scroll,BorderLayout.EAST);
            Iterator itr1 = imageWidgets.iterator();
            /** to get scrollvalue */
            int scrvalue = scroll.getValue();
            /* width,height are the width and height of the imagewidget */
            int width = view.getWidth() / col;
            int height = view.getHeight() / row;
            /* for loop for skipping the images */
            for(int i = 1; i < (scrvalue * col + 1); i++){
                    itr1.next();
            /* dimension for the image */
            Dimension d = new Dimension(view.getWidth() / col, view.getHeight()/ row);
            /* for loops for setting the bounds of the images */
            for(int rn = 0; rn < row; rn++){
               for(int cn = 0; cn < col; cn++){
                    if(itr1.hasNext()){
                         ImageWidget iw = (ImageWidget) itr1.next();
                         view.add(iw);
                         iw.setBounds(cn * d.width, rn * d.height, d.width,d.height);
    }i hope i can find some useful suggestion..
    Thanku

Maybe you are looking for

  • G580 External display monitor

    Hi Lenovo community,  My sister's G580 laptop computer have malfunctioned display screen, also not booting and showing green-pink lines. We are not looking for replacement and repairing of the screen(as warranty is off) and she already have new lapto

  • BDS in BW

    Hello, Can someone provide me with information about BDS in BW? And is it possible to merge the documents into one document? Are there some customizing actions necessary? What is the purpose of the button 'Administration'? Regards, Jos van der Sterre

  • Just regular surfing and it would freeze, never had this on Firefox 4.8, This is rubbish, might as well be using internet explorer

    I would be surfing using firefox, going on websites streaming and all the usual things I have done before with firefox 4.6 & 4.8, and even 5 untill one day in the last month it has froze from time to time, for short periods and long periods. Ironical

  • RDBMSRealm and Group membership

    Hello. I would like to us an RDBMSRealm implementation behind some form of caching implementation. I have looked at and run the RDBMSRealm example that ships with 6.0. The major drawback is that I expect to have some groups where the number of member

  • Weblogic toolkit problem

    I am using weblogic(7.0)webservices toolkit for parsing the xml response through toolkit generated java classes. Please look at the schema I am using. *******************SCHEMA****************************** <xs:complexType name="person"> <xs:sequence