Bizarro Swing JList 模型行为
我的 Swing 应用程序中遇到一个问题,我通过向其传递一个模型来创建一个简单的 JList - 即使模型已明显填充,JList 仍拒绝显示其自己的模型内容。
DefaultListModel dlm = new DefaultListModel();
String[] modelElems = {"Apple", "Orange", "Banana"};
for(int i = 0; i < modelElems.length; i++)
dlm.add(i, modelElems[i]);
JList lstFruitList = new JList(dlm);
lstFruitList.setVisible(true);
当我的 Swing 应用程序运行时,我在屏幕上看到 JList,但它完全是空的!我看过无数的例子,翻阅了 Swing 教程,但似乎无法弄清楚发生了什么。有人以前遇到过这种情况吗?!?有什么明显-明显-错误的事情吗?!?
注意:
以下打印语句确实显示我的模型有 3 个元素:
// Prints "Fruit List model has a size of 3"
System.out.println("Fruit List model has a size of " + dlm.size());
但是,如果我尝试循环并打印模型中水果的名称,请调用(String)dlm.get(i)
在每次迭代时(其中 i
是迭代变量),它将每个模型元素打印为 null
。 ..
嗯嗯
I am having an issue in my Swing app where I am creating a simple JList by passing it a model - and even though the model is demonstrably populated, the JList refuses to display it's own model's contents.
DefaultListModel dlm = new DefaultListModel();
String[] modelElems = {"Apple", "Orange", "Banana"};
for(int i = 0; i < modelElems.length; i++)
dlm.add(i, modelElems[i]);
JList lstFruitList = new JList(dlm);
lstFruitList.setVisible(true);
When my Swing app runs, I see the JList on screen, but it is completely empty! I've looked at countless examples, poured over the Swing tutorials, and cannot seem to figure out what is going on. Anybody ever had this happen to them before?!? Anything that is glaringly-obviously-wrong?!?
NOTE:
The following print statement indeed shows that my model has 3 elements:
// Prints "Fruit List model has a size of 3"
System.out.println("Fruit List model has a size of " + dlm.size());
However, if I try to loop through and print the names of the fruits in my model, by calling (String)dlm.get(i)
at every iteration (where i
is the iteration var), it prints each model element as null
...
hmmmm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码对我来说效果很好。一些想法:
setVisible
,您究竟如何将其添加到您正在显示的内容中?lstFruitList.setBackground(Color.BLUE);
作为参考,这是我运行的代码:
That code works fine for me. Some thoughts:
setVisible
on the JList, how exactly are you adding it to whatever you are displaying?lstFruitList.setBackground(Color.BLUE);
For reference, here's the code that I ran: