I am new to Java Swing.I want to design one JToolBar
. The JToolBar
should be placed in 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);
Read about How to use ToolBars.
The following code is taken straight from the 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 the usage of BorderLayout
here. And do the necessary changes in your code.
UPDATE:
I have tried using your code which shows output like this. I have used addSeparator method with dimension. This is just a try to solve the problem. I am not sure whether this approach is the correct way.
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);
}