简体   繁体   中英

Toolbar doesn't show in Java GUI

Why does the toolbar not show up? I want to put it under the File/help menu...Im recreating the paint application and I want to put the buttons on the toolbar. The menu works fine, I believe that the problem is that the canvas where the user draws is covering it but im not sure. Please help.

contentPane = new JPanel();
setContentPane(contentPane);
CustomCanvas panel = new CustomCanvas();
panel.setBounds(0, 0, this.getWidth(), this.getHeight());
int xx, yy;
contentPane.add(panel);
contentPane.setLayout(null);

JToolBar toolBar = new JToolBar("This is the toolbar");
toolBar.setBounds(0, 0, 800, 50);
toolBar.setVisible(true);

The above code is a bit of a mess because you:

  1. try to replace the content panel with a JPanel
  2. then you try to use a null layout.
  3. then you try to add components to the content pane

The end result is that the CustomCanvas is painting over the toolbar.

Don't do any of the above.

Instead let the layout manager of the content pane to all the work. The default layout for a JFrame is a BorderLayout. So typically you would simply use:

//contentPane.add(toolBar);
add(toolBar, BorderLayout.PAGE_START);

Read the section from the Swing tutorial on How to Use ToolBars for a working example to show you a better program structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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