JComboBox打印所选项目的值

时间:2012-11-09 16:25:19

标签: java swing

我创建了一个组合框:

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

当我调用System.out.println(comboBox.getSelectedItem().toString());以查看所选项目时,我只会看到&lt;选择一个团队&gt;

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

2 个答案:

答案 0 :(得分:1)

这会在你的组合框中添加ActionListener

comboBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println(comboBox.getSelectedItem().toString());
    }
});

答案 1 :(得分: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();
  }
}