与一组单选按钮的功能类似,下拉列表也用来强制用户从一组可能的元素中只选择一个。
不过,这种方法更加紧凑,而且在不会使用户感到迷惑的前提下,改变下拉列表中的内容
更容易(你也可以动态改变单选按钮,不过这显然不合适)。
缺省状态下,JComBox组件与Windows操作系统下的组合框并不完全相同,后者允许你
从列表中选择或者自己输入。要想得到这样的行为,你必须调用setEditable( )方法。使用
JComboBox,你能且只能从列表中选择一个元素。在下面的例子里,JComboBox开始已
经具有一些元素,然后当一个按钮按下的时候,将向组合框中加入新的元素。
//: c14:ComboBoxes.java
// Using drop-down lists.
// <applet code=ComboBoxes width=200 height=125></applet>
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class ComboBoxes extends JApplet {
private String[] description = {
"Ebullient", "Obtuse", "Recalcitrant", "Brilliant",
"Somnescent", "Timorous", "Florid", "Putrescent"
};
private JTextField t = new JTextField(15);
private JComboBox c = new JComboBox();
private JButton b = new JButton("Add items");
private int count = 0;
public void init() {
for(int i = 0; i < 4; i++)
c.addItem(description[count++]);
t.setEditable(false);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(count < description.length)
c.addItem(description[count++]);
}
});
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t.setText("index: "+ c.getSelectedIndex() + " " +
((JComboBox)e.getSource()).getSelectedItem());
}
});
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(t);
cp.add(c);
cp.add(b);
}
public static void main(String[] args) {
Console.run(new ComboBoxes(), 200, 125);
}
} ///:~
上例中的JtextField被用来显示“被选中的索引”(当前被选中元素的序号)和组合框中被
不过,这种方法更加紧凑,而且在不会使用户感到迷惑的前提下,改变下拉列表中的内容
更容易(你也可以动态改变单选按钮,不过这显然不合适)。
缺省状态下,JComBox组件与Windows操作系统下的组合框并不完全相同,后者允许你
从列表中选择或者自己输入。要想得到这样的行为,你必须调用setEditable( )方法。使用
JComboBox,你能且只能从列表中选择一个元素。在下面的例子里,JComboBox开始已
经具有一些元素,然后当一个按钮按下的时候,将向组合框中加入新的元素。
//: c14:ComboBoxes.java
// Using drop-down lists.
// <applet code=ComboBoxes width=200 height=125></applet>
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class ComboBoxes extends JApplet {
private String[] description = {
"Ebullient", "Obtuse", "Recalcitrant", "Brilliant",
"Somnescent", "Timorous", "Florid", "Putrescent"
};
private JTextField t = new JTextField(15);
private JComboBox c = new JComboBox();
private JButton b = new JButton("Add items");
private int count = 0;
public void init() {
for(int i = 0; i < 4; i++)
c.addItem(description[count++]);
t.setEditable(false);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(count < description.length)
c.addItem(description[count++]);
}
});
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t.setText("index: "+ c.getSelectedIndex() + " " +
((JComboBox)e.getSource()).getSelectedItem());
}
});
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(t);
cp.add(c);
cp.add(b);
}
public static void main(String[] args) {
Console.run(new ComboBoxes(), 200, 125);
}
} ///:~
上例中的JtextField被用来显示“被选中的索引”(当前被选中元素的序号)和组合框中被
选中元素的文本。