2017-02-27 56 views
1

是否有任何方法在停靠的JToolBar上绘制停靠在现有面板上的其余组件?如何在面板的其余组件上绘制停靠的JToolBar

基本上我想,当停靠工具栏(从浮动位置),不要干扰我的其他组件和现有的布局。

简单的例子,刚上手..

public class ToolBarSample { 

public static void main(final String args[]) { 
    JFrame frame = new JFrame("JToolBar Example"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JToolBar toolbar = new JToolBar(); 

    toolbar.add(new JButton("button")); 
    toolbar.add(new JButton("button 2")); 

    Container contentPane = frame.getContentPane(); 
    contentPane.add(toolbar, BorderLayout.NORTH); 
    contentPane.add(new JLabel("I want this to be under the toolbar"), BorderLayout.CENTER); 

    // set the toolbar floating 
    ((BasicToolBarUI) toolbar.getUI()).setFloatingLocation(10, 10); 
    ((BasicToolBarUI) toolbar.getUI()).setFloating(true, null); 

    // TODO - after application starts, manually dock the toolbar to any position (north/east...) 

    frame.setSize(250, 100); 
    frame.setVisible(true); 
} 
} 

enter image description here

回答

3

您可以直接添加工具栏到JFrameJLayeredPane

下面是一些有用的文档:How to Use Layered Panes

public static void main(final String args[]) { 
    JFrame frame = new JFrame("JToolBar Example"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JToolBar toolbar = new JToolBar(); 

    toolbar.add(new JButton("button")); 
    toolbar.add(new JButton("button 2")); 

    Container contentPane = frame.getContentPane(); 
    //contentPane.add(toolbar, BorderLayout.NORTH); 
    contentPane.add(new JLabel("I want this to be under the toolbar"), BorderLayout.CENTER); 

    JLayeredPane layeredPane = frame.getLayeredPane(); 
    layeredPane.setLayout(new BorderLayout()); 
    layeredPane.add(toolbar, BorderLayout.NORTH); 

    // set the toolbar floating 
    ((BasicToolBarUI) toolbar.getUI()).setFloatingLocation(10, 10); 
    ((BasicToolBarUI) toolbar.getUI()).setFloating(true, null); 

    // TODO - after application starts, manually dock the toolbar to any position (north/east...) 

    frame.setSize(250, 100); 
    frame.setVisible(true); 
} 
相关问题