Frage

Example of my problem:

I have a main file:

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();
            }
        });
    } 
}

And I have an external object that I'm trying to add as a 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);
    }
}

However, my menu bar doesn't show up at all. When I create a JMenuBar function inside the main file, such as... createMenuBar() and have the same exact code within it, it shows up when I add it to the frame, but when I have it as an external object, it doesn't.

What am I doing wrong?

EDIT: Fixed the error. Refer to the code above.

War es hilfreich?

Lösung

You accidentily defined your constructor as a method. Change the signature to public MenuBar() (without return value) and it should work.

public class MenuBar extends JMenuBar
{
    public MenuBar()
    {
        // constructor code
    }  
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top