How to add JToolBar to the center of JPanel, Java Swing?

I am new to Java Swing.I want to create one JToolBar . JToolBar should be placed in the center of JPanel . Is it possible?

 javax.swing.JPanel pane = new javax.swing.JPanel(); BorderLayout border = new BorderLayout(); pane.setLayout(border); JToolBar toolBar = new JToolBar(); pane.add(toolBar,BorderLayout.CENTER); javax.swing.JButton button1 = new javax.swing.JButton("Click Me"); toolBar.add(button1); 
+4
source share
2 answers

Read about How to use toolbars .

The following code is taken directly from doc .

 public ToolBarDemo() { super(new BorderLayout()); ... JToolBar toolBar = new JToolBar("Still draggable"); addButtons(toolBar); ... setPreferredSize(new Dimension(450, 130)); add(toolBar, BorderLayout.PAGE_START); add(scrollPane, BorderLayout.CENTER); } 

See here BorderLayout . And make the necessary changes to your code.

UPDATE:

I tried using your code that shows the output as follows. I used the addSeparator method with dimension. This is just a try to solve the problem. I am not sure whether this approach is the correct way.

enter image description here

 public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(new BorderLayout()); JToolBar toolBar = new JToolBar(); panel.add(toolBar,BorderLayout.PAGE_START); toolBar.addSeparator(new Dimension(150, 0)); JButton button1 = new JButton("Click Me"); toolBar.add(button1); frame.setLayout(new BorderLayout()); frame.add(panel, BorderLayout.CENTER); frame.setSize(new Dimension(400, 100)); frame.setVisible(true); } 
+4
source

If your JPanel has a BorderLayout and you put the JToolBar in BorderLayout.CENTER and you have the components in NORTH , SOUTH , EAST and WEST , then I don’t see the reason why this did not work.

+3
source

All Articles