如何使用GridBagLayout定位组件? [英] How to position components with GridBagLayout?
问题描述
我是Java编程的新手,我正在尝试制作一个包含两个按钮和一个文本区域的窗口,如下图所示.
我遇到的问题是定位组件.我尝试使用GridLayout
并将窗口分成9行和16个单元格,但后来发现我不能让组件占据比一个单元格更多的空间.我知道我应该使用GridBagLayout
,但我不知道该怎么做.帮助将不胜感激. :)
I am kind of new to Java Programming and I am trying to make a window that contains two buttons and a text area, as seen in the image below.
The problem I encountered though was positioning the components. I tried using GridLayout
and separating the window into 9 rows and 16 cells, but then found I couldn't make components occupy more than a cell. I know I should be using GridBagLayout
but I don't know how exactly. Help would be appreciated. :)
推荐答案
您有很多选择.与其尝试将整个组件布局为一个组件,不如尝试使用复合布局,即通过将UI的各个部分布置在单独的窗格中,并专注于每个部分的个别需求...
You have a number of choices. Instead of trying to layout the whole component in one, try using a compound layout, where by you layout sections of the UI in separate panes and focus on the individual requirements of each section...
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);
}
}
}
这篇关于如何使用GridBagLayout定位组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!