组合框(下拉列表)(Combo box(drop-down list))

与一组单选按钮的功能类似,下拉列表也用来强制用户从一组可能的元素中只选择一个。
不过,这种方法更加紧凑,而且在不会使用户感到迷惑的前提下,改变下拉列表中的内容
更容易(你也可以动态改变单选按钮,不过这显然不合适)。


缺省状态下,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被用来显示“被选中的索引”(当前被选中元素的序号)和组合框中被

选中元素的文本。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值