Search code examples
javaswingjmenujtoolbar

JToolBar not showing


I had a simple drawing application. I need to add a menu and a toolbar on the left side. So now, instead of using a simple JFrame, I'm creating a simple class that extends JFrame. I was able to add the menu following some examples online, but can't figure out how to add a JToolBar. I've tried a few different ways, but nothing works. I don't get an error, everything complies just fine, but I don't see any JToolBar. Here's the code for my JFrame, I hope you can help.

class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;

public Menu(String title) {

    openItem = new JMenuItem("Open...");
    openItem.setMnemonic('O');
    openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));

    saveItem = new JMenuItem("Save");
    saveItem.setMnemonic('S');
    saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));

    saveAsItem = new JMenuItem("Save As...");
    saveAsItem.setMnemonic('S');
    saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));

    // (2) Build  menubar, menus, and add menuitems.
    JMenuBar menubar = new JMenuBar(); 
    JMenu fileMenu = new JMenu("File"); 
    fileMenu.setMnemonic('F');
    menubar.add(fileMenu); 
    fileMenu.add(openItem); 
    fileMenu.addSeparator(); 
    fileMenu.add(saveItem);

    // (3) Add listeners to menu items
    openItem.addActionListener(new OpenAction()); // TODO change

    setJMenuBar(menubar);

    JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
//      JPanel panel = new JPanel();
//      panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    JButton newb = new JButton("new");
    toolbar.add(newb);
//      toolbar.setOpaque(true);
    toolbar.setLocation(100, 100);
    toolbar.setVisible(true);
//      toolbar.setMinimumSize(new Dimension(100, 100));
//      toolbar.setAlignmentX(0);

//      panel.add(toolbar);
    add(toolbar, BorderLayout.NORTH);
    getContentPane().add(toolbar, BorderLayout.NORTH);
//      getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);

    setTitle(title);

    pack();
    setLocationRelativeTo(null);  // Center window.
}

// OpenAction
class OpenAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
    }
}
}

Solution

  • My problem was that I was the way I was instantiating my JFrame. I was using a helper function like this one:

    public static JFrame openInJFrame(Container content, int width, int height,
            String title, Color bgColor) {
    
        // ...
        frame.setContentPane(content);      
    
        frame.setVisible(true);
        return (frame);
    }
    

    So my JToolBar was getting replaced by the Container object...

    Thanks guys! Your answers helped me figure out my problem.