2

我创建了一个组合框:

JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"<Select a Team>", "X", "Y", "Z"}));

当我调用System.out.println(comboBox.getSelectedItem().toString());以查看所选项目时,我只看到 <Select a Team> 。

每次更改组合框的值时,如何打印组合框的值?(我试图搜索如何使用监听器或回调函数,但不明白如何为我的目标实现它)。

4

2 回答 2

1

这将在ActionListener您的组合框中添加一个:

comboBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println(comboBox.getSelectedItem().toString());
    }
});
于 2012-11-09T16:28:11.113 回答
0

试试这个代码。我已经注释掉了对你来说可能很难的行。

    import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame implements ActionListener{
  JComboBox combo = new JComboBox();

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    combo.addItem("A");
    combo.addItem("H");
    combo.addItem("P");
    combo.setEditable(true);
    System.out.println("#items=" + combo.getItemCount());

    //this line is telling the combox that call this class's 
    //actionPerformed method whenver any interesting thing happens
    combo.addActionListener(this);

    getContentPane().add(combo);
    pack();
    setVisible(true);
  }

  //here is the method
  //it will be called every time by combo object whenver any interesting thing happens
  public void actionPerformed(ActionEvent e) {
    System.out.println("Selected index=" + combo.getSelectedIndex()
        + " Selected item=" + combo.getSelectedItem());
      }


  public static void main(String arg[]) {
    new Main();
  }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame implements ActionListener{
  JComboBox combo = new JComboBox();

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    combo.addItem("A");
    combo.addItem("H");
    combo.addItem("P");
    combo.setEditable(true);
    System.out.println("#items=" + combo.getItemCount());

    //this line is telling the combox that call this class's 
    //actionPerformed method whenver any interesting thing happens
    combo.addActionListener(this);

    getContentPane().add(combo);
    pack();
    setVisible(true);
  }

  //here is the method
  //it will be called every time by combo object whenver any interesting thing happens
  public void actionPerformed(ActionEvent e) {
    System.out.println("Selected index=" + combo.getSelectedIndex()
        + " Selected item=" + combo.getSelectedItem());
      }


  public static void main(String arg[]) {
    new Main();
  }
}
于 2012-11-09T16:40:39.760 回答