我正在使用 Java 开发一个非常简单的 GUI。
在此 GUI 中,我想显示:
- 页面顶部带有一些文本的标签
- 上述标签下的 JComboBox
- 上述 JComboBox 下的一个 JButton
这是我的代码:
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Prova {
public static void main(String[] args) {
JFrame frame = new JFrame("A Simple GUI");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocation(430, 100);
JPanel panel = new JPanel();
frame.add(panel);
JLabel lbl = new JLabel("Select one of the possible choices and click OK");
lbl.setVisible(true);
panel.add(lbl);
String[] choices = { "CHOICE 1","CHOICE 2", "CHOICE 3","CHOICE 4","CHOICE 5","CHOICE 6"};
final JComboBox<String> cb = new JComboBox<String>(choices);
cb.setVisible(true);
panel.add(cb);
JButton btn = new JButton("OK");
panel.add(btn);
}
}
不幸的是,我得到的结果是
如图所示,标签、JComboBox 和 JButton 在同一行!
相反,我希望它们如上所述“堆叠”:
J标签
组合框
J按钮
我尝试使用 setLocation(int x, int y) 方法,但它们始终显示在同一位置。
非常感谢!
原文由 NoobNe0 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
frame.setLayout(null);
这将允许您将标签、按钮等放置在您喜欢的位置