帮助使用带有 3 个组合框和一个向量变量的 Swing JFrame
我创建了一个 Swing JFrame
,其中包含 3 个组合框和一个向量变量来填充它们,但在执行代码时所有组合框都是空的。有人可以告诉我出了什么问题吗?
public class Notes extends JFrame {
JFrame jf;
JPanel jp = new JPanel();
Vector<Integer> v = new Vector<Integer>();
int i;
Integer x;
Dimension d = new Dimension(40, 12);
Notes() {
jf = new JFrame("ComboBox Demo");
for (i = 1; i <= 31; i++) {
x = new Integer(i);
v.add(x);
}
JComboBox date = new JComboBox(v);
v.removeAllElements();
for (i = 1; i <= 12; i++) {
x = new Integer(i);
v.add(x);
}
JComboBox month = new JComboBox(v);
v.removeAllElements();
for (i = 2011; i <= 2020; i++) {
x = new Integer(i);
v.add(x);
}
JComboBox year = new JComboBox(v);
v.removeAllElements();
date.setSize(d);
month.setSize(d);
year.setSize(d);
jp.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
jp.add(date);
jp.add(month);
jp.add(year);
jf.add(jp, BorderLayout.PAGE_START);
jf.setSize(300, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String arg[]) {
new Notes();
}
}
I created a Swing JFrame
with 3 comboboxes and a vector variable to populate them, but all comboboxes are empty on execution of code. Can someone tell me what is wrong.
public class Notes extends JFrame {
JFrame jf;
JPanel jp = new JPanel();
Vector<Integer> v = new Vector<Integer>();
int i;
Integer x;
Dimension d = new Dimension(40, 12);
Notes() {
jf = new JFrame("ComboBox Demo");
for (i = 1; i <= 31; i++) {
x = new Integer(i);
v.add(x);
}
JComboBox date = new JComboBox(v);
v.removeAllElements();
for (i = 1; i <= 12; i++) {
x = new Integer(i);
v.add(x);
}
JComboBox month = new JComboBox(v);
v.removeAllElements();
for (i = 2011; i <= 2020; i++) {
x = new Integer(i);
v.add(x);
}
JComboBox year = new JComboBox(v);
v.removeAllElements();
date.setSize(d);
month.setSize(d);
year.setSize(d);
jp.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
jp.add(date);
jp.add(month);
jp.add(year);
jf.add(jp, BorderLayout.PAGE_START);
jf.setSize(300, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String arg[]) {
new Notes();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是非常明显的,因为您要删除向量的所有元素:
当您将 v 传递给 JComboBox 构造函数时,组合框不会复制每个值,而是引用您提供给它的向量。因此,如果您从该向量中删除元素,您将看到一个空的组合框。
如果您这样做是为了在每个 cicle 之后重用 v 变量,请将上面的错误行替换为:
It's pretty obvious because you are removing all elements of your vector:
When you pass v to your JComboBox constructor, the combobox doesn't copy each value but references the Vector you gave to it. So if you remove the elements from that vector, you'll see an empty combo box.
If you were doing this to reuse v variable after each cicle substitute the wrong lines above with :