简体   繁体   English

如何在扩展JPanel的类中添加用于加载/保存文件的菜单栏?

[英]How to add a menu bar for loading/saving files in a class that extends JPanel?

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 : 此刻窗口看起来像这样: 在此处输入图片说明

Thanks 谢谢

您可以添加JMenuBarJToolBar给封闭JFrame ,如图所示这里

JMenuBar添加到JFrame ,而不JPanel(add JMenuBar, BorderLayout.NORTH)JPanel(add JMenuBar, BorderLayout.NORTH) (可能,没有问题,可能不是方法)

This depends. 这取决于。

You could use a BorderLayout , placing the JMenuBar at the NORTH position 您可以使用BorderLayout ,将JMenuBar放置在NORTH位置

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 您需要一种内容窗格,这将允许在CENTRE位置为容器设置不同的布局管理器

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. 另外,您也可以使用SwingUtilities.getAncestorOfClass找到的第一个实例JFrame在父组件层次或SwingUtilities.getWindowAncestor如果你不介意铸造的结果。

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 . 这只是发生在我身上,如果您要使用getAncestorOfClass ,那么最好去寻找JRootPane的实例,该实例具有setJMenuBar It is the responsibility of the JRootPane to layout out the menu bar and content pane (and a few other things) JRootPane负责布局菜单栏和内容窗格(以及其他一些事情)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM