1

Consider the following code :

/**
 * Main class
 * @author X2
 *
 */
class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener ,KeyListener
{
    /**
     *    private variables
     */

    // dimensions of the window
    private static final long serialVersionUID = 1L;
    private static final Dimension MIN_DIM = new Dimension(300, 300);
    private static final Dimension PREF_DIM = new Dimension(500, 500);


    /**
     * Setting the dimensions of the window
     */
    public Dimension getMinimumSize() { return MIN_DIM; }

    public Dimension getPreferredSize() { return PREF_DIM; }



    /**
     *  The constructor
     */
    DrawingPanel()
    {
        super();
        addMouseListener(this);
        addMouseMotionListener(this);
        addKeyListener(this);
        setFocusable(true);
        requestFocusInWindow();
    }

public void paintComponent(Graphics g)
{
// code 
}

public void mouseClicked(MouseEvent evt) 
{ // code 

}

// more code 

How can I add a panel to my window , where I need the options for opening and saving files .

At the moment the window looks like that : enter image description here

Thanks

JAN
  • 21,236
  • 66
  • 181
  • 318

3 Answers3

3

You can add a JMenuBar or a JToolBar to the enclosing JFrame, as shown here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
3

add JMenuBar to the JFrame, not to the JPanel(add JMenuBar, BorderLayout.NORTH) (is possible, no issue, maybe not proepr of way)

mKorbel
  • 109,525
  • 20
  • 134
  • 319
3

This depends.

You could use a BorderLayout, placing the JMenuBar at the NORTH position

The problem then comes down to how do you layout any child components? You'd need one kind of content pane, this would allow to set a different layout manager for the container at the CENTRE position

Alternatively, you could use SwingUtilities.getAncestorOfClass to find the first instance of JFrame in the parent component hierarchy or SwingUtilities.getWindowAncestor if you mind casting the result.

Updated

It just occurred to me, if you were going to use getAncestorOfClass, you would be better off looking for an instance of JRootPane, which has a setJMenuBar. It is the responsibility of the JRootPane to layout out the menu bar and content pane (and a few other things)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366