[英]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.