awt和swing中JComboBox用法,本人感觉这样很不好,但是找不到好的用法,不给我的意图相符,我是想每次选择后就出现当前选择的结果,可是事实不是这样。
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.event.*;
- public class TestComboBox {
- public static void main(String[] args) {
- MyComboBox mcbx = new MyComboBox("测试");
- System.out.println(mcbx.get());
- }
- }
- class MyComboBox extends JFrame {
- JComboBox cbx;
- static int index = 0;
- final String[] test = {"","小孩", "中年", "老年"};
- static String str;
- public MyComboBox(String title) {
- super(title);
- setSize(500,500);
- cbx = new JComboBox(test);
- getContentPane().add(cbx);
- setVisible(true);
- }
- String get() {
- while(str == null) {
- cbx.addItemListener(new ItemListener() {
- public void itemStateChanged(ItemEvent e) {
- index = cbx.getSelectedIndex();
- str = test[index];
- }
- });
- }
- return str;
- }
- }
我觉得不应该用while来判断,而应该用监听器,每次发生变化,结果也变化才对。