关于制作某种格式的JAVA GUI的问题

时间:2010-11-30 21:23:38

标签: java user-interface swing components panel

我正在尝试制作一个如下所示的GUI:

我只知道如何使用BorderLayout,它有5个按钮的空间。北,西,中,东,南。

由于我需要在顶线上有6个组件,这种方法无法工作。我不知道如何制作它以便我可以在顶线上有超过1个组件。是否有其他我可以使用的布局,或者是否有某些方法可以操作BorderLayout以便我可以将6个组件放在最上面?

4 个答案:

答案 0 :(得分:2)

您需要做的是将组件嵌套在其他组件中。例如,顶部(北)应该是一个JPanelJPanel将包含顶部的6个组件。

代码可能类似于以下内容:

JPanel northPane = new JPanel();
northPane.add(new JLabel("Principle: "));
northPane.add(principleTextBox);
... and so on
mainPanel.setLayout(new BorderLayout());
mainPanel.add(northPanel, BorderLayout.NORTH);

中心组件可能是包含两个中心按钮的另一个JPanel。南部组件将是包含单个JPanel或仅JLabel的另一个JLabel

如果您不必在主面板上使用BorderLayout,则可能更容易使用BoxLayout

答案 1 :(得分:2)

我再次转向miglayout,这是Java的绝对最佳布局管理器。没有嵌套的JPanel,只是使用基于字符串的约束的简单布局。

alt text

启用调试模式: alt text

调整窗口大小后(注意文本字段大小的比例保持不变) alt text

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;

/**
 *
 * @author nicholasdunn
 */
public class InterestCalculator extends JPanel {

    public InterestCalculator() {
        super(new MigLayout("debug, fill", "align center"));
        // Make 6 components cram into one cell
        add(new JLabel("Principal:"), "split 6");
        // This textfield grows at twice the normal rate
        add(new JTextField(), "growx 200");
        add(new JLabel("Interest rate (percentage):"));
        // This one at a normal rate
        add(new JTextField(), "growx 100");
        add(new JLabel("Years:"));
        // This one at half the normal rate
        add(new JTextField(), "growx 50, wrap");

        // The row with the two buttons
        add(new JButton("Compute simple interest"), "split 2");
        add(new JButton("Compute compound interest"), "wrap");

        // The result label
        add(new JLabel("The result with simple interest would be"));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new InterestCalculator();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

答案 2 :(得分:1)

如果我正在重新创建该UI,我将使用具有3行1列的GridLayout开始JPanel。在每一栏中,我都会添加一个孩子JPanel。

然后对于每一行,我将使用GridBagLayout来定位组件。

答案 3 :(得分:1)

Here是一个关于布局管理器的教程。

请记住,您始终可以向JPanel添加多个元素,并将特定布局应用于该JPanel。然后你可以嵌套面板(在其他面板中添加面板)。