java awt 选择框
The Choice class provides a pop-up menu to the user. The user is capable of choosing one of the options from the list. The selected item appears at the top. This class is often used when there is a large number of options to choose from and not a lot of space available to display all the items on the screen.
Choice类向用户提供一个弹出菜单。 用户能够从列表中选择选项之一。 所选项目显示在顶部。 当有很多选项可供选择并且没有足够的空间来显示屏幕上的所有项目时,通常使用此类。
We can program to interact with the Choice object at runtime, by implementing the ItemListener interface. The class is capable of firing the ItemEvent objects, which we can handle by assigning an ItemListener. We will discuss more event handling in later sections.
通过实现ItemListener接口,我们可以编程在运行时与Choice对象进行交互。 该类能够触发ItemEvent对象,我们可以通过分配ItemListener来处理该对象。 我们将在后面的部分中讨论更多的事件处理。
Consider the following code -
考虑以下代码-
import java.awt.*;
import javax.swing.*;
public class CreateChoice extends Frame {
CreateChoice() {
Choice c1 = new Choice();
Choice c2 = new Choice();
c1.add("Apple");
c1.add("Banana");
c1.add("Mango");
c2.add("C++");
c2.add("Java");
c2.add("Ruby");
c2.add("Javascript");
c2.add("Python");
System.out.println(c2.getItemCount());
System.out.println(c2.getSelectedItem());
c1.setBounds(50, 50, 100, 30);
c2.setBounds(50, 100, 100, 30);
setLayout(null);
setVisible(true);
setSize(300, 300);
add(c1);
add(c2);
}
public static void main(String[] args) {
CreateChoice ob = new CreateChoice();
}
}
Output
输出量
As can be seen from the output, we obtain two pop up menus, each providing us with a list, with items to choose from. Initially, we have created two empty Choice objects, c1 and c2. The add() method lets us add String objects to c1 and c2.
从输出中可以看出,我们获得了两个弹出菜单,每个菜单都为我们提供了一个列表,以及可供选择的项目。 最初,我们创建了两个空的Choice对象c1和c2 。 add()方法使我们可以将String对象添加到c1和c2 。
String objects are displayed in the list in the same order as added. The Choice class maintains an index value, using which String objects are added. This means that we can access any item on such a list directly from its index.
字符串对象以与添加时相同的顺序显示在列表中。 Choice类维护一个索引值,使用该值添加String对象。 这意味着我们可以直接从其索引访问此列表中的任何项目。
Whatever item the user clicks on, gets selected and is displayed at the top, as can be seen – Apple and C++ are displayed in the two Choice objects.
可以看到,无论用户单击什么项目,都将其选中并显示在顶部,其中Apple和C ++会显示在两个Choice对象中。
Often we require to check the total number of items in a Choice object. For this, we have the getItemCount() method. It returns an integer value, representing the total count of the items. As printed on the screen, there are 5 objects in c2.
通常,我们需要检查Choice对象中的项目总数。 为此,我们有getItemCount()方法。 它返回一个整数值,代表项目的总数。 在屏幕上打印时, c2中有5个对象。
int getItemCount()
We can also retrieve which item is presently selected by the user, using the getSelectedItem() method. It returns a String value, of the object that is selected by the user.
我们还可以使用getSelectedItem()方法检索用户当前选择的项目。 它返回用户选择的对象的字符串值。
String getSelectedItem()
翻译自: https://www.includehelp.com/java/awt-choice.aspx
java awt 选择框