在GUI中使用不同的布局

Kar*_*ren 1 java layout user-interface grid-layout

这是我的程序应该是什么样子,我有点困惑我应该在哪里使用不同的布局.

我有一个Window类调用Panel类,Panel类调用InputPanel和DisplayPanel类.我的InputPanel类调用我的DetailsPanel,CrimePanel和ButtonPanel类,以便它们构成在Input选项卡下看到的内容.我被告知要在整个窗口中使用BorderLayout,并且DetailsPanel(左侧面板)和CrimePanel应该是GridLayout.

这是否意味着我应该:

  1. 将BorderLayout代码放在Panel中,将GridLayout代码放在CrimePanel和DetailsPanel中
  2. 将BorderLayout代码放在Window中,将GridLayout代码放在Panel中?

alt text http://img137.imageshack.us/img137/6422/93381955.jpg

Joe*_*oey 5

好吧,你的描述有点令人困惑(或者我今天仍然太累或者还没有足够的咖啡因).你从别人那里"召集"小组课程的想法也有点奇怪.

但据我所知,你的第一个选择是正确的选择.

通常,您只是在运行时嵌套对象,因此它可能看起来有点像以下内容:

InputPanel (has BorderLayout)
+--DetailsPanel (put in BorderLayout.WEST; has GridLayout)
|  +--nameLabel
|  +--nameTextField
|  +--...
+--CrimePanel (put in BorderLayout.NORTH; has GridLayout)
|  +--murderRadioButton
|  +--arsonRadioButton
|  +--...
+--ButtonPanel (put in BorderLayout.CENTER; has GridLayout)
   +--button
Run Code Online (Sandbox Code Playgroud)

您通常在相应类的构造函数中执行此操作:

public class InputPanel {
    public InputPanel() {
        this.setLayout(new BorderLayout());
        this.add(new DetailsPanel(), BorderLayout.WEST);
        this.add(new CrimePanel(), BorderLayout.NORTH);
        this.add(new ButtonPanel(), BorderLayout.CENTER);
    }
}

public class DetailsPanel {

    JLabel nameLabel;
    JTextField nameField;
    // ...

    public DetailsPanel() {
        this.setLayout(new GridLayout(5, 1));

        nameLabel = new JLabel("Name");
        nameField = new JTextField();
        // ...

        this.add(nameLabel);
        this.add(nameField);
        // ...
    }
}

...
Run Code Online (Sandbox Code Playgroud)

但是,我在这里看到一个小问题:由于GridLayout不允许组件跨越多个列,您可能还需要DetailsPanel在左侧嵌套其他面板.您可以使用GridBagLayout具有所需功能的单个程序,或者在其中嵌套其他面板:

DetailsPanel (has BorderLayout)
+--panel1 (has GridLayout with 2 rows, 1 column; put in BorderLayout.NORTH)
|  +--nameLabel
|  +--nameField
+--panel2 (has GridLayout with 3 rows, 2 columns; put in BorderLayout.CENTER)
   +--dayField
   +--dayLabel
   +--monthField
   +--...
Run Code Online (Sandbox Code Playgroud)