How to select any random value from a dropdown?

怎甘沉沦 提交于 2019-12-02 01:04:41

Well, first get the total number of items in the dropdown. Then generate a random number between 0 and dropdown items count. Then select that number as index to set your dropdown item

Use getSelectOptions to get an array of options of the select box.

Then generate a random integer between 0 (inclusive) and the length of the array (exclusive).

Then use select with an index locator to select the randomly chosen option.

What Sachin said. I know often it's good to get an actual code reply, so assuming you're working with a JComboBox:

comboBox.setSelectedIndex(new Random().nextInt(comboBox.getItemCount()));

The class Random can be found in the java.util package.

First generate a random number between 0 and the number of items in your list. For example:

int random = new Random().nextInt(5);

Then use this random number as the index in your select call:

select("mydropdown", "index=" + random);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!