[英]Getting selected Items from Jlist
I have seen many posts & tried different ways to solve this problem but still I dont get my list of selected items. 我看过很多文章,并尝试了不同的方法来解决此问题,但仍然没有得到所选项目的列表。 Here's the code which I use.
这是我使用的代码。
public List<String> getSelectedDeviceList()
{
return list;
}
/**
* Create the frame.
*/
public JLogicDesign(Frame frame, List<String> listDevices) {
super();
setTitle("Device Names");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 331, 316);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
jlistModel = new DefaultListModel();
for(String s: listDevices)
{
jlistModel.addElement(s);
}
final JList jlist = new JList(jlistModel);
jlist.setVisibleRowCount(5);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
list = new ArrayList<String>();
Object[] values = jlist.getSelectedValues();
for(Object o: values)
{
list.add(o.toString());
}
dispose();
}
});
The JList is being properly populated. JList已正确填充。 When I try to get the selected Items, I get a NPE.
当我尝试获取所选项目时,我得到了NPE。
This is another class where I'm calling the above class 这是我在上一堂课的另一堂课
JLogicDesign jld = new JLogicDesign(f,listOfDevices);
devices = new ArrayList<String>();
devices = jld.getSelectedDeviceList();
Thanks in advance !! 提前致谢 !!
You get NPE at this line: 您会在此行获得NPE:
JLogicDesign jld = new JLogicDesign(f,listOfDevices);
devices = new ArrayList<String>();
devices = jld.getSelectedDeviceList(); // NPE here
Because list
variable in JLogicDesign
is only initialized when btnOk
is pressed. 由于
list
中的变量JLogicDesign
时才初始化btnOk
被按下。 So the pointed line is executed before this button is pressed and that's why it throws NPE. 因此,在按下此按钮之前执行了指针,这就是它引发NPE的原因。
To avoid NPE you shoud initialize list
in JLogicDesign
. 为了避免NPE,您应该在
JLogicDesign
初始化list
。 However it doesn't solve the problem. 但是,它不能解决问题。 You wont get NPE but you'll get an empty list.
您不会得到NPE,但会得到一个空列表。 This is because
JLogicDesign
is not modal and even if these sentences are being executed on the Event Dispatch Thread jld.getSelectedDeviceList()
will return the list
before btnOk
is pressed. 这是因为
JLogicDesign
不是模态的,即使这些语句在事件调度线程上执行, jld.getSelectedDeviceList()
也会在按下btnOk
之前返回list
。
If you need the selected devices before continue then consider use a modal JDialog
. 如果在继续之前需要选定的设备,请考虑使用模式
JDialog
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.