我在使用我在Controller类中填充的数组字符串生成下拉列表时遇到问题。该列表显示在GUI中,但不包含任何值。我是否错误地使用了getter / setter方法?尽管查看了JComboBoxes的Oracle文档,但我一直无法找到示例。 api引用了我认为我使用不正确的setModel方法。任何人都可以提供一个简单的例子吗?
package example;
import javax.swing.*;
public class MyApp extends JFrame {
JTabbedPane tabbedPane = new JTabbedPane();
View view = new View();
ColourView colourView = new ColourView();
Controller controller = new Controller(colourView);
public MyApp() {
tabbedPane.add("First Tab", colourView);
getContentPane().add(tabbedPane);
}
package example;
import javax.swing.*;
public class ColourView extends View {
private JLabel colourLabel;
private JComboBox comboBox;
public ColourView() {
colourLabel = new JLabel();
colourLabel.setText("Colours");
colourLabel.setBounds(20, 30, 70, 20);
mainContentLayeredPane.add(colourLabel, JLayeredPane.DEFAULT_LAYER);
comboBox = new JComboBox();
comboBox.setSize(100, 20);
mainContentLayeredPane.add(comboBox, JLayeredPane.DEFAULT_LAYER);
}
public void setComboBox(String[] list) {
comboBox.setModel(new DefaultComboBoxModel());
for (Object item : list) {
comboBox.addItem(item);
}
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
MyApp app = new MyApp();
app.setVisible(true);
app.setSize(600, 600);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
package example;
import java.util.ListIterator;
public class Controller {
private ColourView colourView;
ListIterator<String> litr;
String listData[] = {"Item 1", "Item 2", "Item 3", "Item 4"};
Controller(ColourView colourView) {
this.colourView = colourView;;
}
public void getListData() {
colourView.setComboBox(listData);
}
}
答案 0 :(得分:2)
您必须将元素添加到ComboboxModel
,如下所示:
// define model
DefaultComboBoxModel model;
...
public void setComboBox(String[] list) {
model = new DefaultComboBoxModel(list);
comboBox.setModel(model);
}
注意:如果要修改元素,则必须再次在模型中修改它,而不是在ComboBox本身中修改它。