在jListbox Java Netbeans中选择项目



早上好,

我目前正在处理一个项目,该项目涉及从列表框中选择一项。

列表框中项目的格式如下:(航空公司名称(#(最大重量(kgs。

我的第一个问题是尝试从列表框中获取项目。我尝试过很多东西,比如list.getSelectedIndex((;并使用for循环来遍历索引以尝试和比较";i〃;一家航空公司的名字,但没有用。

其次,你们对我如何从我的绳子(SAA#25kg(中提取最大重量部分有什么建议吗。我的字符串处理/操作不是很好,如果有任何建议,我将不胜感激。我的第一个想法是使用.split((,但之后我也会得到25公斤。

我正在使用的列表框如下所示:https://gyazo.com/328ddeb9b7888821cfe74fecb551dd08

谨向 IzzVoid致意

要从JList中获取所选值,您需要执行以下操作:

String stringItem = jList1.getSelectedValue().trim();

从所选列表项中获取重量:

// Is something in JList selected.
if (jList1.getSelectedIndex() != -1) {
// Yes...Get the selected item from JList.
String stringItem = jList1.getSelectedValue().trim();
System.out.println("Selected List Item: " + stringItem);  //Display it.
// Split the JList item based on the Hash character into a String Array.
String[] itemParts = stringItem.split("#");
// Are there two elements within the Array?
if (itemParts.length > 1) {
// Yes...Then the 2nd element must be the weight
String item = itemParts[0];                     // Get ite related to weight
System.out.println("Item: " + item);            // Display item 

String stringWeight = itemParts[1];             // get weight related to item
System.out.println("Weight: " + stringWeight);  // Display weight

// Convert weight String to double data type...
// Remove everything not a digit and convert to double.
double weight = Double.valueOf(stringWeight.replaceAll("[^\d]", "")); 
System.out.println("Weight (as double type): " + weight);  // Display weight
}
else {
// No...there is only a single element - Assume No Weight is available!
System.out.println("No Weight Available!");
}
}
// No...Nothing appears to be selected in JList.
else {
System.out.println("Nothing selected!");
}

最新更新