在一个JFrame中使用两个JPanel

时间:2012-10-24 21:13:15

标签: java swing user-interface layout

我正在尝试创建一个程序,允许用户单击按钮将某些内容放在JPanel中并允许他们移动此项目。我已经找到了一个很好的布局来使用移动组件(参见this链接)。但是,我只是好奇创建这样的布局的最佳方法?我希望有这样的事情:

layout idea

我怎样才能做到这一点?我想使用两个JPanel或其他什么吗?

2 个答案:

答案 0 :(得分:10)

主面板(或窗口内容窗格)必须有BorderLayout作为布局管理器。

然后,按钮面板将添加到BorderLayout.WEST,拖动面板将添加到BorderLayout.CENTER

有一个Visual Guide来摆放布局管理器。

答案 1 :(得分:6)

尝试使用JSplitPane

enter image description here

这是一个代码示例:

class SplitPane extends JFrame {

private     JSplitPane  splitPaneV;
private     JSplitPane  splitPaneH;
private     JPanel      panel1;
private     JPanel      panel2;
private     JPanel      panel3;


public SplitPane(){
    setTitle( "Split Pane Application" );
    setBackground( Color.gray );

    JPanel topPanel = new JPanel();
    topPanel.setLayout( new BorderLayout() );
    getContentPane().add( topPanel );

    // Create the panels
    createPanel1();
    createPanel2();
    createPanel3();

    // Create a splitter pane
    splitPaneV = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
    topPanel.add( splitPaneV, BorderLayout.CENTER );

    splitPaneH = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT );
    splitPaneH.setLeftComponent( panel1 );
    splitPaneH.setRightComponent( panel2 );

    splitPaneV.setLeftComponent( splitPaneH );
    splitPaneV.setRightComponent( panel3 );
}

public void createPanel1(){
    panel1 = new JPanel();
    panel1.setLayout( new BorderLayout() );

    // Add some buttons
    panel1.add( new JButton( "North" ), BorderLayout.NORTH );
    panel1.add( new JButton( "South" ), BorderLayout.SOUTH );
    panel1.add( new JButton( "East" ), BorderLayout.EAST );
    panel1.add( new JButton( "West" ), BorderLayout.WEST );
    panel1.add( new JButton( "Center" ), BorderLayout.CENTER );

}

public void createPanel2(){
    panel2 = new JPanel();
    panel2.setLayout( new FlowLayout() );

    panel2.add( new JButton( "Button 1" ) );
    panel2.add( new JButton( "Button 2" ) );
    panel2.add( new JButton( "Button 3" ) );
}

public void createPanel3(){
    panel3 = new JPanel();
    panel3.setLayout( new BorderLayout() );
    panel3.setPreferredSize( new Dimension( 400, 100 ) );
    panel3.setMinimumSize( new Dimension( 100, 50 ) );

    panel3.add( new JLabel( "Notes:" ), BorderLayout.NORTH );
    panel3.add( new JTextArea(), BorderLayout.CENTER );
}

public static void main( String args[] ){
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
    // Create an instance of the test application
    SplitPane mainFrame = new SplitPane();
    mainFrame.pack();
    mainFrame.setVisible( true );
}
}

您可以使用splitPaneH.setOneTouchExpandable true / false

您可以为这两者分配分隔符位置:

Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    int width = d.width;
    int height = d.height;

    spane.setDividerLocation((width*3)/4);
    spanex.setDividerLocation(width/4);