【发布时间】:2014-03-19 12:47:33
【问题描述】:
我正在用 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 在同一行!
相反,我希望它们如上所述“堆叠”:
JLabel
JComboBox
JButton
我尝试使用 setLocation(int x, int y) 方法,但它们总是显示在相同的位置。
非常感谢!
【问题讨论】:
标签: java user-interface jbutton jlabel jcombobox