import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class ComboBox{
  JComboBox combo;
  JTextField txt;
  JFrame frame;
  public static void main(String[] args) {
    ComboBox b = new ComboBox();
  }  public ComboBox(){
    String course[] = {"BCA","MCA","PPC","CIC"};
    frame = new JFrame("Creating a JComboBox Component");
    JPanel panel = new JPanel();
    combo = new JComboBox(course);
    combo.setBackground(Color.gray);
    combo.setForeground(Color.red);
    txt = new JTextField(10);
    panel.add(combo);
    panel.add(txt);
    frame.add(panel);
    combo.addItemListener(new ItemListener(){
      public void itemStateChanged(ItemEvent ie){ //
       doSomething();
      }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,400);
    frame.setVisible(true);
  }
  public void doSomething() {
      String str = (String)combo.getSelectedItem();
      txt.setText(str);
      JOptionPane.showMessageDialog(frame, "Are you sure?", "information", 1);
  }
  
}如上代码,combobox值变化后,弹出一个对话框。问题是:我需要点两下鼠标才能关掉对话框。第一下,下拉框收回,第二下关掉对话框。
有哪位大侠能告诉我能一下鼠标搞定吗?
我想达到的效果是,下拉框选值后,弹出对话框,鼠标一下把对话框关掉。
一种解决方案是:JOptionPane.showMessageDialog(frame, "Are you sure?", "information", 1);
改成JOptionPane.showMessageDialog(null, "Are you sure?", "information", 1);
这样可以实现,但问题是,加入我的电脑有两个屏幕,我把frame拖到右边屏幕,对话框出现在左边屏幕,非常令人费解。所以不能null,这样对话框才会出现在frame中间。
非常感谢!

解决方案 »

  1.   

    额,其实这个和下拉消失无关,是因为itemStateChanged这个会被触发两次
    if(ie.getStateChange() == ItemEvent.SELECTED){
        // your codes
    }
    这样应该就好如果要下拉收回去的话,可以用开启线程的方式一下为我修改的代码
    combo.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent ie) { //
    if (ie.getStateChange() == ItemEvent.SELECTED) {
    Thread t = new Thread() {
    public void run() {
    doSomething();
    }
    };
    t.start();
    }
    }
    });
      

  2.   

    如果是为了选择而触发事件。    combo.addActionListener((new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
    doSomething();
    }
        }));添加ActionListener就行了