【发布时间】:2018-08-23 03:57:18
【问题描述】:
我已经尝试了一段时间来完成这项工作。 我在网上看了很多教程和示例,似乎没有任何帮助。
组合框和标签都位于框架中间的正下方。
我知道需要GridBagConstraints,并且每次添加新组件时都需要设置gbc。
我正在这样做,所以我不确定为什么它不起作用。
还有为什么它会在中心? 如果有的话,它不应该在左上角吗?
public class Application {
ArrayList listOfTickers = new ArrayList();
JFrame frame;
JPanel panel;
JLabel jLabel;
GridBagLayout layout;
GridBagConstraints gbc;
JComboBox comboBox;
Application(ArrayList listOfTickers) throws BadLocationException {
this.listOfTickers = listOfTickers;
setLabels();
setComboBox(listOfTickers);
setFrameAndPanel();
addComponents();
closeFrame();
}
private void addComponents() {
addobjects(jLabel, panel, layout, gbc, 1, 3, 4, 2);
addobjects(comboBox, panel, layout, gbc, 3, 0, 2, 1);
}
private void setLabels() {
jLabel = new JLabel("test");
}
private void closeFrame() {
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private void setComboBox(ArrayList listOfTickers) throws BadLocationException {
comboBox = new JComboBox(listOfTickers.toArray());
comboBox.addActionListener(e -> {
String ticker = comboBox.getSelectedItem().toString();
});
}
private void setFrameAndPanel() {
frame = new JFrame("JFrame Example");
panel = new JPanel();
layout = new GridBagLayout();
panel.setLayout(layout);
frame.getContentPane().setLayout(layout);
gbc = new GridBagConstraints();
frame.add(panel);
frame.setSize(600, 600);
}
public void addobjects(Component component, Container panel, GridBagLayout layout, GridBagConstraints gbc, int gridx, int gridy, int gridwidth, int gridheight) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
layout.setConstraints(component, gbc);
panel.add(component, gbc);
}
}
【问题讨论】:
-
“还有,为什么它会在中间?如果有的话,它不应该在左上角吗?” - 不,这就是
GridBagLayout的工作原理(而且,是的,是时候动动脑筋了) -
就我个人而言,我会避免使用
addobjects样式编码,因为它极大地限制了您可以做什么或要求您为每个可能的参数组合编写方法 -
你还会发现
gridWidth和gridHeight如果你使用不当会弄乱布局 -
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2) 以最小尺寸提供 ASCII 艺术或 GUI 的 预期 布局的简单绘图,如果可调整大小,则具有更大的宽度和高度 - 以显示应如何使用额外空间。
标签: java swing jpanel layout-manager gridbaglayout