gpt4 book ai didi

java - 如何使用 GridBagLayout 定位组件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:10:24 25 4
gpt4 key购买 nike

我是 Java 编程的新手,我正在尝试制作一个包含两个按钮和一个文本区域的窗口,如下图所示。 我遇到的问题是定位组件。我尝试使用 GridLayout 并将窗口分成 9 行和 16 个单元格,但后来发现我无法让组件占用超过一个单元格。我知道我应该使用 GridBagLayout 但我不知 Prop 体如何。帮助将不胜感激。 :)

最佳答案

您有多种选择。与其尝试将整个组件布局为一个,不如尝试使用复合布局,您可以在单独的 Pane 中布局 UI 的各个部分,并专注于每个部分的单独需求...

enter image description here

public class TestLayout11 {

public static void main(String[] args) {
new TestLayout11();
}

public TestLayout11() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ExamplePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

protected class ExamplePane extends JPanel {

public ExamplePane() {
setLayout(new GridBagLayout());

JPanel buttonPane = new JPanel(new GridBagLayout());

JButton btnOkay = new JButton("Ok");
JButton btnCancel = new JButton("Cancel");

JTextArea textArea = new JTextArea(5, 20);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.CENTER;
buttonPane.add(btnOkay, gbc);
gbc.gridy++;
gbc.insets = new Insets(50, 0, 0, 0);
buttonPane.add(btnCancel, gbc);

gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(100, 100, 100, 100);
add(buttonPane, gbc);

gbc.insets = new Insets(150, 100, 150, 100);
gbc.gridx++;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(textArea), gbc);
}
}
}

关于java - 如何使用 GridBagLayout 定位组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com