如何添加主文件之外的swing组件?

时间:2013-05-31 10:20:51

标签: java swing jmenu jmenubar

我的问题示例:

我有一个主文件:

public class APP extends JFrame
{
    private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

    public APP()
    {
        setLayout(new BorderLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setJMenuBar(new MenuBar());

        JPanel content = new JPanel(new GridLayout(0, 8, 2, 2));
        add(new JScrollPane(content, 22, 32), BorderLayout.CENTER);      

        pack();
        setLocationByPlatform(true);
        setResizable(false);
        setVisible(true);
    }

    public Dimension getPreferredSize()
    {
        return new Dimension(screen.width / 10 * 7, screen.height / 10 * 6);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                APP program = new APP();
            }
        });
    } 
}

我有一个外部对象,我试图添加为JMenuBar:

public class MenuBar extends JMenuBar
{
    public MenuBar()
    {
        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);
        add(file);

        JMenuItem item;

        item = new JMenuItem("Add New");
        item.setMnemonic(KeyEvent.VK_N);
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
                ActionEvent.ALT_MASK));
        item.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                //createThumb();
            }
        });
        file.add(item);
    }
}

但是,我的菜单栏根本没有出现。当我在主文件中创建一个JMenuBar函数,例如... createMenuBar()并且在其中具有相同的确切代码时,它会在我将其添加到框架时显示,但是当我将它作为外部对象时,它会显示没有。

我做错了什么?

编辑:修正了错误。请参阅上面的代码。

1 个答案:

答案 0 :(得分:2)

您不小心将构造函数定义为方法。将签名更改为public MenuBar()(不带返回值),它应该可以正常工作。

public class MenuBar extends JMenuBar
{
    public MenuBar()
    {
        // constructor code
    }  
}