[英]Allow JComboBox to accept List<String> or HashMap instead of String[]
When inputting a new Student
object inside my JTables I would like to hold all the localities/cities inside my JComboBox. 在JTables中输入新的
Student
对象时,我想将JComboBox中的所有地点/城市都保存起来。 Each city is stored inside a HashMap
which holds the name as key(as there are no duplicates) and it's postcode. 每个城市都存储在
HashMap
内,该HashMap
将名称保留为键(因为没有重复项),并且是邮政编码。
Example: hashMap.put("City", "AAA")
示例:
hashMap.put("City", "AAA")
Now my issue would be to represent the HashMap
OR List<String>
inside the JComboBox itself. 现在,我的问题是在JComboBox本身内部表示
HashMap
OR List<String>
。 The cheap and easy alternative was to simply re-write the String[]
to hold all the town names and switch-case
the selected value but there are few issues with that: 便宜又容易的选择是简单地重写
String[]
来保存所有城镇名称并switch-case
所选的值,但是这样做几乎没有问题:
Here you go : 干得好 :
String [] string = {"city","town","country","province"};
java.util.List<String> list = new ArrayList<String>(Arrays.asList(string));
Object[] arrayObject= list.toArray();
String [] data = Arrays.copyOf(arrayObject, arrayObject.length,String[].class); // java 1.6+
JComboBox<String> combo = new JComboBox<>( data);
Actually you can do : 实际上,您可以:
String [] string = {"city","town","country","province"};
java.util.List<String> list = new ArrayList<String>(Arrays.asList(string));
JComboBox< java.util.List<String>> combo = new JComboBox<>( );
combo.addItem(list);
but , for every single elemen of JComboxBox
will hold all elements of list in a row. 但是,对于
JComboxBox
每个元素,它都将行中包含列表的所有元素。
*To prevent ambiguity between java.util.List
& java.awt.List
, we should declare them clearly. *为了防止在
java.util.List
和java.awt.List
之间产生歧义,我们应该明确声明它们。
Here the complete demo : 这里是完整的演示:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class ComboBoxDemo extends JFrame {
public ComboBoxDemo() {
super("JComboBox Demo");
String [] string = {"city","town","country","province"};
java.util.List<String> list = new ArrayList<String>(Arrays.asList(string));
Object[] arrayObject= list.toArray();
String [] data = Arrays.copyOf(arrayObject, arrayObject.length,String[].class); // java 1.6+
JComboBox<String> combo = new JComboBox<>( data);
setLayout(new FlowLayout(FlowLayout.CENTER));
add(combo, BorderLayout.CENTER);
}
public static void main(String[] args) {
ComboBoxDemo g = new ComboBoxDemo();
g.setVisible(true);
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.setBounds(100, 100, 300, 300);
}
}
And the result of 和的结果
JComboBox< java.util.List<String>> combo = new JComboBox<>( ); combo.addItem(list);
declaration : 宣言 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.