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 に答える