閱讀關於How to use ToolBars。
以下代碼直接從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);
}
見BorderLayout
這裏的用法。並在代碼中進行必要的更改。
UPDATE:
我一直在使用你的代碼,這樣表示輸出試過。我已經使用尺寸爲addSeparator的方法。 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);
}
如果已經使用再_BorderLayout_其他張貼代碼嘗試這將是非常難以猜測。 – Amarnath
1)請參閱[在JPanel上居中定位JLabel](http://stackoverflow.com/a/7181197/418556)獲取提示。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –