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

Similar Messages

  • Adding Canvas3D image to a JPanel or JFrame

    My team has developed a 3D game board and we want to add it to a JPanel. The test code below works fine but we want to add this to a JPanel. Can you put a Canvas3D in a JPanel?
    import java.applet.Applet;
    import java.awt.BorderLayout;
    import java.awt.Frame;
    import java.awt.event.*;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.universe.*;
    import com.sun.j3d.utils.geometry.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import java.awt.event.*;
    import java.util.Enumeration;
    import com.sun.j3d.utils.behaviors.mouse.*;
    import com.sun.j3d.utils.behaviors.keyboard.*;
    public class ProxyBoard extends Applet
         public class SimpleBehave extends Behavior
              private TransformGroup targetTG;
              private Transform3D rotation = new Transform3D();
              private double angle = 0.0;
              SimpleBehave(TransformGroup targetTG)
                   this.targetTG = targetTG;
              public void initialize()
                   this.wakeupOn(new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
              public void processStimulus(Enumeration criteria)
                   angle +=0.05;
                   rotation.rotX(angle);
                   targetTG.setTransform(rotation);
                   this.wakeupOn(new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
         public ProxyBoard()
              setLayout(new BorderLayout());
              Canvas3D canvas3D = new Canvas3D(null);
              add("Center", canvas3D);
              SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
              simpleU.getViewingPlatform().setNominalViewingTransform();
              BranchGroup scene = createSceneGraph(simpleU);
              scene.compile();
              simpleU.addBranchGraph(scene);
         public BranchGroup createSceneGraph(SimpleUniverse su)
              BranchGroup boardBG = new BranchGroup();
              TransformGroup vpTrans = null;
              BoundingSphere mouseBounds = null;
              vpTrans = su.getViewingPlatform().getViewPlatformTransform();
              mouseBounds = new BoundingSphere(new Point3d(), 1000.0);
              KeyNavigatorBehavior keyNavBeh = new KeyNavigatorBehavior(vpTrans);
              keyNavBeh.setSchedulingBounds(mouseBounds);
              boardBG.addChild(keyNavBeh);
              MouseRotate myMouseRotate = new MouseRotate(MouseBehavior.INVERT_INPUT);
              myMouseRotate.setTransformGroup(vpTrans);
              myMouseRotate.setSchedulingBounds(mouseBounds);
              boardBG.addChild(myMouseRotate);
              MouseTranslate myMouseTranslate = new MouseTranslate(MouseBehavior.INVERT_INPUT);
              myMouseTranslate.setTransformGroup(vpTrans);
              myMouseTranslate.setSchedulingBounds(mouseBounds);
              boardBG.addChild(myMouseTranslate);
              MouseZoom myMouseZoom = new MouseZoom(MouseBehavior.INVERT_INPUT);
              myMouseZoom.setTransformGroup(vpTrans);
              myMouseZoom.setSchedulingBounds(mouseBounds);
              boardBG.addChild(myMouseZoom);
              Board board = new Board();
              Transform3D pegPositions[] = new Transform3D[8];
              TransformGroup pegPositionsTG[] = new TransformGroup[8];
              Pegs pegs[] = new Pegs[8];
              Transform3D translate = new Transform3D();
              translate.set(new Vector3f(0.0f, -1.0f, -5.0f));
              TransformGroup boardTGT1 = new TransformGroup(translate);
              TransformGroup boardTGR1 = new TransformGroup();
              boardTGR1.setCapability(boardTGR1.ALLOW_TRANSFORM_WRITE);
              for(int i = 0; i < 8; i++)
                   pegs[i] = new Pegs();
                   pegPositions[i] = new Transform3D();
                   pegPositions.set(new Vector3f(-2.5f, 0, (float)(-i/4.0)));
                   pegPositionsTG[i] = new TransformGroup(pegPositions[i]);
                   pegPositionsTG[i].addChild(pegs[i].getTransformGroup());
                   boardTGT1.addChild(pegPositionsTG[i]);               
              boardTGR1.addChild(board.getBoard());
              SimpleBehave myRotate = new SimpleBehave(boardTGR1);
              myRotate.setSchedulingBounds(new BoundingSphere());
              boardBG.addChild(myRotate);
              boardTGT1.addChild(boardTGR1);
              boardBG.addChild(boardTGT1);                    
              boardBG.compile();
              return boardBG;
         public static void main(String[] args)
              Frame frame = new MainFrame(new ProxyBoard(), 800, 600);
    /*-------------Main Source Container------------------*/
    public class Proxy extends JFrame
         implements MouseMotionListener
         private JDesktopPane myDesktop;
         private JPanel panel;
         private JLabel statusBar, position;
         private JSlider zSlide, zSlide1;
         private ImageIcon test;
         private int i;
         public Proxy()
              super("Proxy Board Prototype 1.2.2");
              i=0;
              statusBar = new JLabel();
              getContentPane();
              myDesktop = new JDesktopPane();
              getContentPane().add(myDesktop);
    public static void main(String args[])
              Proxy app = new Proxy();
              //new MainFrame( new Proxy(), 800, 600 );
    //          app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    /*-------------JPanel I want to hold to the 3D Graphics--------*/
    class Session extends JPanel
         implements MouseMotionListener
         private ImageIcon test;
         private JLabel position;
         private JSlider zSlide;
         private JPanel panel, gPanel;
         static int openFrameCount = 0;
         public Session()
              //super("", true, true, true, true);
              setLayout(new FlowLayout());
              openFrameCount++;
         //setTitle("Untitled Message " + openFrameCount);
    ProxyBoard pb = new ProxyBoard();//<-Graphic Class
    gPanel = new JPanel();
    gPanel.add(pb);//<-I want the 3D Graphic here
              test = new ImageIcon("Layout.jpg");
              JLabel pic = new JLabel(test);
              addMouseMotionListener( this );
              zSlide = new JSlider(SwingConstants.VERTICAL, 600, 10);
              zSlide.setMajorTickSpacing(25);
              zSlide.setPaintTicks(true);
              zSlide.setToolTipText("Zoom");
              panel.add(zSlide, BorderLayout.NORTH);
              panel.add(gPanel, BorderLayout.CENTER);//<-Graphic Here
              panel.add(position, BorderLayout.SOUTH);
              add(panel);
              //pack();
              setSize(200,200);
              setVisible (true);

    Yes you can. Just use the add method of JPanel. However note this
    http://www.j3d.org/faq/swing.html (specially read this: http://java.sun.com/products/jfc/tsc/articles/mixing/)
    when mixing Lightweight (JPanel) and Heavyweight (Canvas3D) components.

  • Adding and displaying a new JPanel -- not working as expected

    I'm starting my own new thread that is based on a problem discussed in another person's thread that can be found here in the New to Java forum titled "ActionListener:
    http://forum.java.sun.com/thread.jspa?threadID=5207301
    What I want to do: press a button which adds a new panel into another panel (the parentPane), and display the changes. The Actionlistener-derived class (AddPaneAction) for the button is in it's own file (it's not an internal class), and I pass a reference to the parentPane in the AddPaneAction's constructor as a parameter argument.
    What works: After the button is clicked the AddPaneAction's actionPerformed method is called without problem.
    What doesn't work: The new JPanel (called bluePanel) is not displayed as I thought it would be after I call
            parentPane.revalidate();  // this doesn't work
            parentPane.repaint(); 
    What also doesn't work: So I obtained a reference to the main app's JFrame (I called it myFrame) by recursively calling component.getParent( ), no problem there, and then tried (and failed to show the bluePanel with) this:
            myFrame.invalidate();  // I tried this with and without calling this method here
            myFrame.validate();  // I tried this with and without calling this method here
            myFrame.repaint();
    What finally works but confuses me: I got it to work but only after calling this:
            myFrame.pack(); 
            myFrame.repaint();But I didn't think that I needed to call pack to display the panel. So, what am I doing wrong? Why are my expectations not correct? Here's my complete code/SSCCE below. Many thanks in advance.
    Pete
    The ParentPane class:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class ParentPane extends JPanel
        private JButton addPaneBtn = new JButton("Add new Pane");
        public ParentPane()
            super();
            setLayout(new BorderLayout());
            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            setBackground(Color.yellow);
            JPanel northPane = new JPanel();
            northPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            northPane.setBackground(Color.yellow);
            northPane.add(addPaneBtn);
            add(northPane, BorderLayout.NORTH);
            // add our actionlistener object and pass it a reference
            // to the main class which happens to be a JPanel (this)
            addPaneBtn.addActionListener(new AddPaneAction(this));
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
        private static void createAndShowGUI()
            JFrame frame = new JFrame("test add panel");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new ParentPane());
            frame.pack();
            frame.setVisible(true);
    } the AddPaneAction class:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    public class AddPaneAction implements ActionListener
        private JPanel parentPane;
        private JFrame myFrame;
        public AddPaneAction(JPanel parentPane)
            this.parentPane = parentPane;
         * recursively get the JFrame that holds the parentPane panel.
        private JFrame getJFrame(Component comp)
            Component parentComponent = comp.getParent();
            if (parentComponent instanceof JFrame)
                return (JFrame)parentComponent;
            else
                return getJFrame(parentComponent);
        public void actionPerformed(ActionEvent arg0)
            JPanel bluePanel = new JPanel(new BorderLayout());
            bluePanel.setBackground(Color.blue);
            bluePanel.setPreferredSize(new Dimension(400, 300));
            JLabel myLabel = new JLabel("blue panel label");
            myLabel.setForeground(Color.LIGHT_GRAY);
            myLabel.setVerticalAlignment(SwingConstants.CENTER);
            myLabel.setHorizontalAlignment(SwingConstants.CENTER);
            bluePanel.add(myLabel, BorderLayout.CENTER);
            parentPane.add(bluePanel);
            myFrame = getJFrame(parentPane);
            //parentPane.revalidate();  // this doesn't work
            //parentPane.repaint(); 
            //myFrame.invalidate(); // and also this doesn't work
            //myFrame.validate();
            //myFrame.repaint();
            myFrame.pack();  // but this does!?
            myFrame.repaint();
    }

    For me (as it happens I'm using JDK 1.5.0_04) your code appears to work fine.
    It may be that we're seeing the same thing but interpreting it differently.
    1. When I run your application with your "working" code, and press the button then the JFrame resizes and the blue area appears.
    2. When I run your application with your "not working" code and press the button then the JFrame does not resize. If I manually resize it then the blue area is there.
    3. When I run your application with your "not working" code, resize it first and then press the button then the JFrame then the blue area is there.
    I interpret all of this as correct behaviour.
    Is this what you are seeing too?
    Are you expecting revalidate, repaint, invalidate or validate to resize your JFrame? I do not.
    As an aside, I do remember having problems with this kind of thing in earlier JVMs (e.g. various 1.2 and 1.3), but I haven't used it enough recently to know if your code would manifest one of the previous problems or not. Also I don't know if they've fixed any stuff in this area.

  • Adding an image to a JPanel

    Can some one tell me how to place an image file (.gif, .jpeg etc) to a JPanel when the user selects it from a JFileChooser???
    Please help me...it is getting urgent and this stoopid book doesn't help me growls
    Something to do with ImageIcon and a paintComponent method??? shrugs

    reason I posted a new msg wasn't cos I didn't get a reply...more that what I asked for was not really what I wanted (wasn't specific enough).
    When I looked, my old msg wasn't on the main screen so I thought it would be ok to made a new one.
    But I'm sorry, I won't do it again :)

  • Adding Dynamically adding a component to a JPanel and make it diaplay

    Hi,
    I am having two panels in a container, one is in the left side and the another is in the right side.The left side panel contains some buttons.If the user clicks on any buttons the corresponding component is to be loaded to the right side panel and displayed.This should be done at runtime.

    Hi,
    I will tell you the design & senario, my screen has two panels one is in leftside & another is in rightside of the screen.while opening the main screen I am having 3 buttons on the leftside panel and none in the rightside panel.If i clicked the 1st button 2 labels,2 textfields and 2 buttons should be displayed on the rightside panel.I am having these components in a separate class file which extends a JPanel.Only in the runtime i want to add this class file(as component) to the rightside panel in the main screen.how is it possible? reply me

  • Adding noSwing component into Swing JPanel.

    Helo.
    I was wondering is there any chance to add button created using SWT library to Swing JPanel? Mamy someone did do this before?
    Thanks for any clue.
    Regards

    This begs the question: why on earth would you want to do this?
    I imagine it's possible through some monumental JNI coding, but the chances of it working well are slight and of breaking often are great. So again, why?

  • 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

  • Adding directional blur to adjustment layer/nested sequence

    When adding a directional blur to adjustment layer or a nested sequence in MPE hardware mode the sides get dark (alpha channel shows).
    When turning MPE off the issue is gone.
    Already submitted a bugreport but found out its MPE hardware.
    Seen this issue in a previous version of Premiere. Think it was fixed then, but now its back.
    MPE on:
    MPE off: this is how it should be.
    Can someone test this, and see it its reproducable.
    Message was edited by: Ann Bens

    This is how it looks for me when I take a extension with a alpha channel over a simple BG and turn Cuda on then turn Cuda off.
    The image above is with GPU acceleration turned on.
    This image below this sentence is with software on.
    In a way it appears simliar to your findings since when my GPU accleration is turned on you can see a white boarder creeping up from the bottom and top but with it off you don't see it.
    However when I turn the blur up higher and try it again I get these results.
    GPU On in the image directly below.
    GPU off in the image below this sentence.
    I'm using the exact same blur settings in both images... In the top image you can see that white is taking over the picture.
    This has GPU on in the image below this sentence.
    This is Software only on in the pic below this sentence.
    Not really sure if this confirms anything for you or not though. Just figured I'd post it cause the issue seemed intresting to me. Anyways though here were my findings.

  • Printing JPanel that is added to the JScrollPane

    Hi
    I am facing a typical problem while I am printing my JPanel.
    My Panel is added to the JScrollPane.And I added 200 Images to the JPanel (20 rows and 10 columns).
    To see the 6,7,8,9,10 Images I have to scroll it left side and for 80 to 200 images I have to scroll down.
    Now if i print my JPanel it is only printing the Images those are visible to the user at a time. If scroll down and say print again it is printing the bottom components and missing Top components (Images).
    I want to print all the images at a time.
    Can any body suggest me how to do it. My Panel implements Printable interface and the following is the print method that I implemented
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    componentToBePrinted.paintAll(g2d);
    return(PAGE_EXISTS);
    Thank you and Regards
    Kiran Kumar Vasireddy

    could you publish the entire code or at least your paintall method....
    Loic

  • Cannot See Components Added To JComponent

    Hi,
    It seems that components added to direct descendents of JComponent are not visible. Please see the following pseudocode:
    // In the following b is NOT visible:
    class MyComponent extends JComponent{}
    b = JButton("OK")
    p = MyComponent()
    p.add(b)
    f = JFrame()
    f.contentPane.add(p)
    f.show()
    // In the following b IS visible:
    b = JButton("OK")
    p = JPanel()
    p.add(b)
    f = JFrame()
    f.contentPane.add(p)
    f.show()
    How does one make JComponent-added components visible?
    Thanx
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Components and Containers are a bit different. Try calling paintChildren on your custom component like this:
    public void paintComponent(Graphics g){
       ...//do what you need to
       paintChildren(g);

  • JMenu and JList

    I want to hava a menu that would have some of the same functionality as a JList, such as the cell renderer, the borders and the list models. I'm working inside a JApplet so creating JPopupMenus are out because of it seems to open new Windows in browsers and has that ugly Applet Window warning.
    I want to open pop up menus over the list elements.
    For example, I have a JList that holds user names for a chat room. When an element in that JList is clicked I want to open a menu that lists commands like "go to users homepage", "private chat", "kick out", etc.
    I've written an applet that uses JMenus. But I'd like to have the user list remain a JList because my applet uses the ListModel to pass the list's content to different parts of the program.
    I'd like to have similar functionality to the following (but with a JList instead of a JMenuBar holding the contents of the list)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTestApplet extends JApplet{
    JPanel p = new JPanel(new BorderLayout());
    JMenuBar menuBar = new JMenuBar();
    JScrollPane scroll;
    public MenuTestApplet(){
         getContentPane().add(p, BorderLayout.CENTER);
         menuBar.setBackground(Color.blue.brighter().brighter());
         menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.Y_AXIS));
         for (int i=1; i<50;i++){
         addNewMenu("Menu "+i);
         p.add(new JLabel("nothing here"), BorderLayout.CENTER);
         scroll = new JScrollPane(menuBar);
         p.add(scroll, BorderLayout.CENTER);
    public void addNewMenu(String title){
         JMenu m = new JMenu(title);
         m.setBackground(Color.blue.brighter());
         JMenuItem item = new JMenuItem("one");
         item.setBackground(Color.blue.brighter());
         m.add(item);
         item = new JMenuItem("two");
         item.setBackground(Color.blue.brighter());
         m.add(item);
         item = new JMenuItem("THR33");
         item.setBackground(Color.blue.brighter());
         m.add(item);     
         m.setMinimumSize(m.getPreferredSize());
         m.setMenuLocation(7, 3);
         menuBar.add(m);
    I'm just looking for ideas right now.
    thanks

    would simply adding JMenu's to the JList do the trick?
    this was suggested by someone to me, but I thought that the elements in the JList are simply painted panels that use the objects toString() in the CellRenderer.

  • Display an image on a JPanel

    Hi,
    I am confused about all the MediaTracker and BufferedImage class used to display an image file (e.g. GIF or JPG) on a JPanel
    Can someone provide the steps and also the code snippet of the JPanel's paint() method?
    I want to display an image directly on the JPanel.
    Thank you.

    "the scrollpane doesn't work" is not very descriptive.
    So I can't help you with that problem.
    The suggested code given to you may not work in all
    situations:
    1) super.paintComponent(..) tells the panel to paint
    all its children (in case you've added any other
    components to the panel).
    2) drawImage() tells the panel to draw the image over
    top of all the children (which defeats the whole
    purpose of doing the super.paintComponent())
    The safer order should be:
    1) drawImage()
    2) setOpaque( false )
    3) super.paintComponent().
    This approach will then work for adding images to the
    background of a textArea, textPane etc.Good point that I did not consider since my JPanel is exclusively used for an image with no components added.
    If your image is known not to have an alpha channel, you could setOpaque(false) in the extended JPanel's constructor and avoid recalling for every paint (as I am able to do in my situation). You'll probably want to do this in otherwise:
    setOpaque(true);
    drawImage(image,x,y,observer);
    setOpaque(false);
    super.paintComponent(g);
    since the next call to paintComponent() will already be setOpaque(false) (unless it is automatically reset, which I haven't seen).
    Robert Templeton

  • Need help:JPanel not being displayed in the JFrame

    Hello,
    I have a class called ConstructRoom.java which extends JFrame and another class called DimensionsPanel.java which extends JPanel. In the ConstructRoom class I use the following theContainer.add(new DimensionsPanel());, so I can display my JPanel. Well I get the JFrame but no JPanel. When the this call is made the DimensionsPanel.java code is cycled through, Where has my JPanel gone to?
    If I change the DimensionPanel.java extend JFrame and add the the JFrame code. Then I get the JFrame and the JPanel.
    Whats going on here?
    Thanks

    I made some of the changes with no luck. Here is some of the code:
    ---------from ConstructRoom.java--------
    //Imports
    public class ConstructRoom extends JFrame
    //----Member objects and varibles
    private static String theTitle; //Varible for title of frame
    private JFrame theFrame; //Object for the JFrame
    // ----------------------------------------------------------- ConstructRoom
    public ConstructRoom(String theTitle)
    super(theTitle); //JFrame super class
    theFrame = new JFrame("My frame");
    Container theContainer = theFrame.getContentPane(); //Frame container
    theContainer.setLayout(new FlowLayout());
    theContainer.add(new DimensionsPanel());
    theFrame.pack();
    theFrame.setBounds(10,10,400, 400);
    theFrame.addWindowListener(new WindowHandler());
    theFrame.setVisible(true);
    }//end ConstructRoom(String theTitle)
    // -------------------------------------------------------------------- main
    public static void main(String args[])
    ConstructRoom theRoom = new ConstructRoom(theTitle);
    }//end main(String args[])
    //----WindowHander
    }//end class ConstructRoom extends JFrame
    --------from DimensionsPanel.java
    //Imports
    public class DimensionsPanel extends JPanel
    //----Member objects and varibles
    private JPanel dimensionsPanel; //The main panel to hold all info
    private Box panelBox; //Box for all boxes which is added to the JPanel
    private Box furnListBox; //Box for all related items of the furnList
    private Box dimensionsBox; //Box for all dimensions (x, y, z)
    private Box xFieldBox; //Box for all related items of the xField
    private Box yFieldBox; //Box for related items of the yField
    private Box zFieldBox; //Box for related items of the zField
    private Box buttonsBox; //Box for all buttons
    private Box clearBox; //Box for related clear button items
    private Box buildBox; //Box for related build button items
    private JLabel furnListLabel; //Label for the furnList comboBox
    private JLabel xFieldLabel; //Label for the xField
    private JLabel yFieldLabel; //Label for yField
    private JLabel zFieldLabel; //Label for zField
    private JTextField xField; //Text field to enter the x dimension
    private JTextField yField; //Text field to enter the y dimension
    private JTextField zField; //Text field to enter the z dimension
    private JComboBox furnList; //List of selectable furniture objects
    private JButton clearButton; //Clear button
    private JButton buildButton; //Build button
    // --------------------------------------------------------- DimensionsPanel
    public DimensionsPanel()
    //----Setting up dimensions panel
    dimensionsPanel = new JPanel();
    dimensionsPanel.setLayout(new BorderLayout());
    dimensionsPanel.setPreferredSize(new Dimension(150,150));
    dimensionsPanel.setBorder(new TitledBorder(new EtchedBorder(),
    "Select Furniture and Enter Dimensions"));
    //----Initializing GUI components
    furnListLabel = new JLabel("Select from list ");
    furnList = new JComboBox();
    xFieldLabel = new JLabel("Enter Width ");
    xField = new JTextField();
    yFieldLabel = new JLabel("Enter Height ");
    yField = new JTextField();
    zFieldLabel = new JLabel("Enter Depth ");
    zField = new JTextField();
    buildButton = new JButton("Build Object");
    clearButton = new JButton("Clear Object");
    //-----Setting up the combo box and adding items
    furnList.addActionListener(new ComboProcessor());
    furnList.addItem(" "); //Default item
    furnList.addItem("Color Cube");
    furnList.setMaximumRowCount(6); //Max number of items before scrolling
    furnList.setSelectedItem(" "); //Set initial to default item
    //--Add the furnList to its box for placement in the JPanel
    furnListBox = Box.createHorizontalBox();
    furnListBox.add(Box.createHorizontalStrut(5));
    furnListBox.add(furnListLabel); //Adding the combo box label
    furnListBox.add(furnList); //Adding the combo box
    furnListBox.add(Box.createHorizontalStrut(5)); //Spacing
    //-------------------------------- Start Dimensions Components
    //----Setting up the xField
    xField.setEnabled(false); //Disabled at start
    xField.setFocusTraversalKeysEnabled(false); //Disabling the Tab Key
    //----Adding the event listeners
    xField.addActionListener(new XTextProcessor()); //Enter Key
    xField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the xField to its box for placement in the dimensionsBox
    xFieldBox = Box.createHorizontalBox();
    xFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    xFieldBox.add(Box.createGlue()); //Take up extra space
    xFieldBox.add(xFieldLabel); //Adding the text field label
    xFieldBox.add(xField); //Adding the text field
    xFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the yfield
    yField.setEnabled(false); //Disabled at start
    yField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    yField.addActionListener(new YTextProcessor()); //Enter Key
    yField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the yField to its box for placement in the dimensionsBox
    yFieldBox = Box.createHorizontalBox();
    yFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    yFieldBox.add(Box.createGlue()); //Take up extra space
    yFieldBox.add(yFieldLabel); //Adding the text field label
    yFieldBox.add(yField); //Adding the text field
    yFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the zfield
    zField.setEnabled(false); //Disabled at start
    zField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    zField.addActionListener(new ZTextProcessor()); //Enter Key
    zField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the zField to its box for placement in the dimensionsBox
    zFieldBox = Box.createHorizontalBox();
    zFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    zFieldBox.add(Box.createGlue()); //Take up extra space
    zFieldBox.add(zFieldLabel); //Adding the text field label
    zFieldBox.add(zField); //Adding the text field
    zFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Adding all dimension components to the dimensionsBox
    dimensionsBox = Box.createVerticalBox();
    dimensionsBox.add(xFieldBox); //Adding the xFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(yFieldBox); //Adding the yFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(zFieldBox); //Adding the zFieldBox
    //-------------------------------- End Dimension Components
    //----Setting up the clearButton
    clearButton.setEnabled(false); //Disabled at start
    //----Adding the event listener
    clearButton.addActionListener(new ClearProcessor());
    //--Add the clear button to its box for placement
    clearBox = Box.createHorizontalBox();
    clearBox.add(Box.createHorizontalStrut(5)); //Spacing
    clearBox.add(clearButton); //Adding the clearButton
    //----Setting up the buildButton
    buildButton.setEnabled(false); //Disabled at start
    //--Add the action listener here
    buildBox = Box.createHorizontalBox();
    buildBox.add(buildButton); //Adding the buildButton
    buildBox.add(Box.createHorizontalStrut(5)); //Spacing
    //----Adding both buttons the buttonsBox
    buttonsBox = Box.createHorizontalBox();
    buttonsBox.add(clearBox); //Adding the clearBox
    buttonsBox.add(Box.createHorizontalStrut(10)); //Spacing
    buttonsBox.add(buildBox); //Adding the buildBox
    //----Create the JPanel (dimensionsPanel)
    //--Creating the main box to be added to the JPanel
    panelBox = Box.createVerticalBox();
    panelBox.add(furnListBox); //Adding the furnListBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(dimensionsBox); //Adding the dimensionBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(buttonsBox); //Adding the buttonsBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsPanel.add(panelBox); //Adding all components to the JPanel
    System.out.println("end dimensionpanel");
    }//end DimensionsPanel()
    //------ActionListeners
    }//end class DimensionsPanel extends JPanel

  • How to enable a scrollbar in a JPanel

    Hi
    I am adding some components in a JPanel and I am adding the JPanel to a JScrollPane.The JScrollPane is finally added to the container.Now I could manage to get only the scrollbars added but it does not work!How should I use the scrollbars to view all the components that are added inside the JPanel.
    Here is my source code:
    tagPanel = new JPanel();
    tagPanel.setLayout(new FlowLayout());
    tagPanel.setPreferredSize(new Dimension(100,100));
    tagPanel.setBackground(Color.white);
    tagPanel.setAutoscrolls(true);
    for(int i = 0; i<=20; i++)
    tempButton = new JButton("Testing");
    tagPanel.add(tempButton);
    container.add(forbiddenscroll= new JScrollPane
    (tagPanel),BorderLayout.WEST);
    forbiddenscroll.setHorizontalScrollBarPolicy
    (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    forbiddenscroll.setVerticalScrollBarPolicy
    (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    Thank you for your reply!
    Your help is very much appreciated.

    don't set prefered size of the tag panel.
    run this code pasted below. it work fine.
    regards,
    Pratap
    import java.awt.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
         JScrollPane forbiddenscroll;
         JPanel tagPanel;
         JButton tempButton;
         public Frame1() {
              tagPanel = new JPanel();
              tagPanel.setLayout(new FlowLayout());
              tagPanel.setBackground(Color.white);
              tagPanel.setAutoscrolls(true);
              for(int i = 0; i<=20; i++)
                   tempButton = new JButton("Testing");
                   tagPanel.add(tempButton);
              forbiddenscroll = new JScrollPane();
              forbiddenscroll.getViewport().setView(tagPanel);
              getContentPane().add(forbiddenscroll, BorderLayout.CENTER);
              forbiddenscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
              forbiddenscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         public static void main(String[] args) {
              Frame1 f = new Frame1();
              f.pack();
              f.setLocation(200,200);
              f.show();
    }

  • Problem with jpanel zooming

    friends,
    i have a jpanel with image as background and i am adding jlabels dynamically to the jpanel. i have to move the jlabel on the image so i added mouse listener to jlabel. now i want to add zooming functionality to the jpanel.
    now if zoom out jpanel everything works well but jlabel mouse listener location is not changing so if i click on jlabel its not activating listener - i need to click outside of jlabel/jpanel (its original location when its 100% zoom) to activate the listener. how can i correct this ?
    thanks in advance
    i will add example after i cutdown (its part of big application)

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class PP3 extends JFrame {
        private JButton btnStart;
        private JButton btnStop;
        private JLabel logoLabel;
        private JSlider zoom;
        private JPanel mainPanel;
        private JPanel btnPanel;
        private JScrollPane jspane;
        private BackPanel3 secondPanel;
        private boolean start = false;
        public PP3() {
            initComponents();
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void initComponents() {
            logoLabel = new JLabel();
            mainPanel = new JPanel();
            btnPanel = new JPanel();
            btnStart = new JButton();
            btnStop = new JButton();
            zoom = new JSlider(0,100,100);
            setBackground(Color.white);
            setLayout(new BorderLayout());
            mainPanel.setBackground(Color.white);
            mainPanel.setBorder(new EtchedBorder());
            mainPanel.setPreferredSize(new Dimension(650, 600));
            mainPanel.setLayout(new CardLayout());
            jspane = new JScrollPane(getSecondPanel());
            mainPanel.add(jspane,"Second Panel");
            add(mainPanel, BorderLayout.CENTER);
            btnPanel.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weighty = 1.0;
            gbc.gridwidth = gbc.REMAINDER;
            btnPanel.setBackground(Color.white);
            btnPanel.setBorder(new EtchedBorder());
            btnPanel.setPreferredSize(new Dimension(150, 600));
            btnStart.setText("Start Labelling");
            btnPanel.add(btnStart, gbc);
            btnStart.setEnabled(true);
            btnStart.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    start = true;
                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                    if(secondPanel != null){
                        secondPanel.setStart(start);
                        Cursor moveCursor = new Cursor(Cursor.TEXT_CURSOR);
                        secondPanel.setCursor(moveCursor);
            btnStop.setText("Done Labelling");
            btnPanel.add(btnStop, gbc);
            btnStop.setEnabled(false);
            btnStop.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    start = false;
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    if(secondPanel != null){
                        secondPanel.setStart(start);
                        Cursor moveCursor = new Cursor(Cursor.DEFAULT_CURSOR);
                        secondPanel.setCursor(moveCursor);
            final JLabel zoomLabel = new JLabel("Zoom");
            zoomLabel.setBorder(BorderFactory.createEtchedBorder());
            gbc.weighty = 0;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            btnPanel.add(zoomLabel, gbc);
            btnPanel.add(zoom, gbc);
            zoom.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent ce) {
                    JSlider source = (JSlider)ce.getSource();
                    if(secondPanel != null) {
                        secondPanel.setZoomFactor((double)source.getValue());
                        zoomLabel.setText("Zoom = " + source.getValue()/100.0);
            String id = "<html><nobr>show label</nobr><br><center>locations";
            JCheckBox check = new JCheckBox(id, secondPanel.showLocations);
            check.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    secondPanel.toggleShowLocations();
            gbc.weighty = 1.0;
            gbc.fill = GridBagConstraints.NONE;
            btnPanel.add(check, gbc);
            add(btnPanel, BorderLayout.EAST);
            pack();
        public JPanel getSecondPanel() {
            if(secondPanel == null) {
                secondPanel = new BackPanel3("images/cougar.jpg", 850, 1100);
                secondPanel.setStart(false);
            return secondPanel;
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PP3();
    class BackPanel3 extends JPanel implements MouseListener,
                                               MouseMotionListener{
        String imgPath = null;
        BufferedImage image;
        private int width = 0;
        private int height = 0;
        private double zoomFactor = 1.0;
        private boolean start = false;
        private boolean same = false;
        Cursor hourglassCursor = new Cursor(Cursor.MOVE_CURSOR);
        // choose a declaration according to your java version
        List<JLabel> labels;     // declaration for j2se 1.5+
    //    List labels;           // j2se 1.4-
        JLabel lastSelected;
        boolean showLocations;
        JLabel selectedLabel;
        boolean dragging;
        Point offset;
        int count = 0;
        private static String SELECTED = "selected";
        public BackPanel3(String path, int width, int height){
            setLayout(null);
            this.width = width;
            this.height = height;
            setPreferredSize(new Dimension(width,height));
            addMouseListener(this);
            addMouseMotionListener(this);
            // chose an instantiation according to your java version
            labels = new ArrayList<JLabel>();    // j2se 1.5+
    //        labels = new ArrayList();          // j2se 1.4-
            lastSelected = new JLabel();
            lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
            showLocations = true;
            dragging = false;
            offset = new Point();
            this.imgPath = path;
            setImage();
        public void setImage(){
            try{
                image = getImage(imgPath);
            }catch(Exception e){
                System.out.println(" (init) ERROR: " + e);
                e.printStackTrace();
        public void setStart(boolean flag){
            start = flag;
        public void setZoomFactor(double zoom){
            zoomFactor = (zoom/100);
            setPreferredSize(new Dimension((int)(850*zoomFactor), (int)(1100*zoomFactor)));
            repaint();
            revalidate();
        public double getZoomFactor(){
            return zoomFactor;
        public void toggleShowLocations() {
            showLocations = !showLocations;
            repaint();
        public void mouseClicked(MouseEvent e) {
            if(start){
                JLabel msgLabel = new JLabel("Test " + count++);
                this.add(msgLabel);
                Dimension d = msgLabel.getPreferredSize();
                msgLabel.setBounds(e.getX(), e.getY(), d.width, d.height);
                labels.add(msgLabel);
                msgLabel.putClientProperty(SELECTED, Boolean.FALSE);
                return;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            for(int j = 0; j < labels.size(); j++) {
                JLabel label = (JLabel)labels.get(j);
                Rectangle bounds = label.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
                Shape xs = at.createTransformedShape(bounds);
                if(xs.contains(p)) {
                    selectedLabel = label;
                    Rectangle r = xs.getBounds();
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                    break;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent me){
            if(dragging) {
                Rectangle bounds = selectedLabel.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(1.0/zoomFactor, 1.0/zoomFactor);
                Point2D p = at.transform(me.getPoint(), null);
                int x = (int)(p.getX() - offset.x);
                int y = (int)(p.getY() - offset.y);
                selectedLabel.setLocation(x, y);
                repaint();
        public void mouseMoved(MouseEvent me){
            if(labels.size() == 0)
                return;
            Point p = me.getPoint();
            boolean hovering = false;
            boolean selectionChanged = false;
            for(int j = 0; j < labels.size(); j++) {
                final JLabel label = (JLabel)labels.get(j);
                Rectangle r = label.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
                Shape scaledBounds = at.createTransformedShape(r);
                if(scaledBounds.contains(p)) {
                    hovering = true;
                    if(!((Boolean)label.getClientProperty(SELECTED)).booleanValue()) {
                        label.putClientProperty("selected", Boolean.TRUE);
                        setCursor(hourglassCursor);
                        if(lastSelected != label)  // for only one JLabel
                            lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
                        lastSelected = label;
                        selectionChanged = true;
                        break;
            // reset lastSelected when there is no selection/hovering
            if(!hovering &&
                ((Boolean)lastSelected.getClientProperty(SELECTED)).booleanValue()) {
                lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
                setCursor(Cursor.getDefaultCursor());
                selectionChanged = true;
            if(selectionChanged)
                repaint();
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.scale(zoomFactor, zoomFactor);
            g2.drawImage(image, 0, 0, this);
            if(showLocations) {
                // show bounds of the actual JLabel children
                // components as they exist on this component
                AffineTransform at = AffineTransform.getScaleInstance(1.0/zoomFactor,
                                                                      1.0/zoomFactor);
                g2.setPaint(Color.blue);
                Component[] c = getComponents();
                for(int j = 0; j < c.length; j++)
                    g2.draw(at.createTransformedShape(c[j].getBounds()));
            // show selected label
            g2.setPaint(Color.red);
            for(int j = 0; j < labels.size(); j++) {
                JLabel label = (JLabel)labels.get(j);
                if(((Boolean)label.getClientProperty("selected")).booleanValue()) {
                    g2.draw(label.getBounds());
                    break;
        protected BufferedImage getImage(String path){
            try{
                URL imgURL = BackPanel3.class.getResource(path);
                if (imgURL == null &&
                       (path.indexOf(":\\") > 0 || path.indexOf(":/") > 0))
                    imgURL = new URL("file:///"+path);
                return getImage(imgURL);
            }catch(MalformedURLException mue){
                System.out.println("error "+mue);
            return null;
        protected BufferedImage getImage(URL url){
            try{
                if (url != null) {
                    BufferedImage source = ImageIO.read(url);
                    double xScale = (double)width / source.getWidth();
                    double yScale = (double)height / source.getHeight();
                    double scale = Math.min(xScale, yScale);
                    int w = (int)(scale*source.getWidth());
                    int h = (int)(scale*source.getHeight());
                    BufferedImage scaled = new BufferedImage(w, h, source.getType());
                    Graphics2D g2 = scaled.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                        RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                    // scales faster than getScaledInstance
                    AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
                    g2.drawRenderedImage(source, at);
                    g2.dispose();
                    return scaled;
                }else{
                    return null;
            }catch(IOException ioe){
                System.out.println("read error "+ioe);
                return null;
    }

Maybe you are looking for

  • MDT 2013 won't capture 8.1 image, does not boot to PE to capture

    I am doing this with Server 2012 R2 and MDT 2013, and the reference machines are VMs I initially created a deployment share for creating windows 7 and windows 8.1 reference images and capturing and deployment worked ok. After getting into some more d

  • Purchase order release table

    Hi, we have a purchase order release strategy defined in our company. I am trying to make a SAP query that will show the list of purchase orders that are hanging for approval. I am trying to find the table that hold the information of which purchase

  • Possible to adjust video camera quality settings?

    I realize this is a shot in the dark, but is there any way to adjust the video camera quality settings on a 5th-gen nano? I'm wondering if the poor quality of the video is a result of the hardware or the built-in compression settings.

  • Spry Tabbed Panels content open verticaly on web site opening?

    Hello, As long as the client does'nt authorised javascript my opening web site page does'nt make sense, we see all the content of the tabs openned vertically. Is there a way to have an acceptable opening page , maybe without the the tabs working for

  • Maximum contacts in palm desktop 6

    I'm trying to import my contacts into Palm desktop...  I have about 650 contacts - what's the max I can import?  Can I split up the file and import smaller chunks at once? Post relates to: Treo 650 (Unlocked GSM)