我正在用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)方法,但它们总是显示在相同的位置。
非常感谢!