首页 > 解决方案 > 从 jlistbox 中的给定值中选择最大值

问题描述

在此处输入图像描述

在此处输入图像描述

我想从 jListBox 中已经存在的值中获取最大值。我该怎么做?我附上了图片。例如列出的图像中的最大值是 4536。我如何从查询中获取这个值?

标签: javalistboxnetbeans-8

解决方案


你可以这样做(阅读代码中的注释):

ListModel model = jList1.getModel();   // Get the JList model...
int highest = 0;        // Will hold the highest list integer value.
int desiredIndex = 0;   // will hold the list index value of highest list integer value.
// Iterate through the elements in JList model.
for (int i = 0; i < model.getSize(); i++) {
    String listItem = model.getElementAt(i).toString(); // place current element into a variable
    // Is the current list item a numerical Value (RegEx used here)
    if (listItem.matches("\\d+")) {
        // Yes it is...
        int val = Integer.parseInt(listItem); // Convert string numerical value to a Integer value 
        // Is this list value higher that what is in the highest variable?
        if (val > highest) {
            // Yes it is...
            highest = val;      // Make hiighest hold the new highest value
            desiredIndex = i;   // Hold the index number of where this value is located within the list.
        }
    }
    // No it isn't...loop again.
}

// Iteration is complete...
System.out.println("Highest value is: " + highest); // Print highest value to console.
jList1.setSelectedIndex(desiredIndex);  // Select the highest value within the JList.
// Done!

推荐阅读