[英]Question about making a JAVA GUI of a certain format
我正在尝试制作一个看起来像这样的GUI:
我只知道如何使用具有5个按钮空间的BorderLayout。 北,西,中,东和南。
由于我需要在顶部有6个组件,因此这种方法行不通。 我不确定如何做到这一点,这样我就可以在第一行上包含多个组件。 还有其他可以使用的布局,还是可以操纵BorderLayout的某种方式,以便可以在顶部放置6个组件?
您需要做的是将组件嵌套在其他组件中。 例如,顶部(北)应为一个JPanel
。 该JPanel
将在顶部包含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
。 South组件将是另一个JPanel
其中包含单个JLabel
或仅包含JLabel
。
如果您不必在主面板上使用BorderLayout
,则使用BoxLayout
可能会更容易。
我再次转向miglayout ,这是Java绝对最佳的布局管理器。 没有嵌套的JPanels,只有使用基于字符串的约束的简单布局。
打开调试模式:
调整窗口大小后(请注意文本字段的大小比例保持不变)
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);
}
}
如果要重新创建该UI,我将从使用3行1列GridLayout的JPanel开始。 在每一列中,我将添加一个子JPanel。
然后,对于每一行,我将使用GridBagLayout定位组件。
这是有关布局管理器的教程。
请记住,您始终可以将多个元素添加到一个JPanel并将特定的布局应用于该JPanel。 然后,您可以嵌套面板(在其他面板中添加面板)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.