[英]Java - Array JList, Print out a Value
I have a JList that is filled with an Array. 我有一个用数组填充的JList。 I just want to print the value when the user selects something in the list and presses a button.
我只想在用户在列表中选择某项并按下按钮时打印该值。 I know it's something to do with getSelectedValues.
我知道这与getSelectedValues有关。 When I searched online I got solutions to JLists filled with addItems but not when filled with an Array.
当我在线搜索时,我得到了用addItems填充的JLists的解决方案,但是当用Array填充时却没有。
This is the code for the button at the moment: 这是当前按钮的代码:
public void actionPerformed(ActionEvent evt) {
Object[] selected = FilmList.getSelectedValues();
String[] selectedItems = new String[selected.length];
System.out.println(selectedItems);
}
The name of my JList is FilmList and the name of my array is films. 我的JList的名称是FilmList,而我的数组的名称是films。 Thanks guys.
多谢你们。
public void actionPerformed(ActionEvent evt) {
Object[] selectedFilms = FilmList.getSelectedValues();
for(int i = 0; i < selectedFilms.length; i++)
System.out.print(selectedFilms[i].toString + ", ");
System.out.println();
}
May be you can do it shorter? 也许您可以做得更短? Something like this?
像这样吗
EDIT 编辑
you should use 你应该使用
Object[] selected = FilmList.getSelectedValues(); System.out.println(java.util.Arrays.toString(selected));
OR If you want to store it in array of String you can do like this: 或如果要将其存储在String数组中,则可以执行以下操作:
String[] selectedItems = new String[selected.length];
for (int i = 0 ; i < selectedItems.length ; i++)
{
selectedItems[i] = (String)selected[i];
}
And then you can print the same as: 然后,您可以打印如下内容:
System.out.println(Arrays.toString(selectedItems));
You can also print the values using for loop as: 您也可以使用for循环将值打印为:
for (int i =0; i < selectedItems.length ; i++)
System.out.println(selectedItems[i]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.