2012-04-11 7 views
0

私は、textField内のテキストを設定するアクションを引き起こすcomboBoxを持つ問題があります。コードは次のとおりです。windowbuilder textfieldがコンボボックスで動作しない

public class Main extends JFrame implements ActionListener{ 
    private JPanel contentPane; 
    private JTextField textField; 
    private JComboBox comboBox; 

    //public static void main - nothing much in it except Main frame = new Main(); 

    public Main() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 563, 407); 
    contentPane = new JPanel(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    setContentPane(contentPane); 
    contentPane.setLayout(null); 
    comboBox.addActionListener(frame); 
    textField = new JTextField(); 
    textField.setBounds(42, 99, 445, 235); 
    textField.setText("HERE"); 
    contentPane.add(textField); 
    textField.setColumns(10); 
    comboBox = new JComboBox(); 
    comboBox.setModel(new DefaultComboBoxModel(new String[] {"Bob", "Dan ", "Emily"})); 
    comboBox.setBounds(42, 48, 140, 29); 
    contentPane.add(comboBox); 

    /*ONE WAY OF DOING IT: comboBox.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 
     textField.setText(studentOutputString((String)comboBox.getSelectedItem())); 
     textField.setText("BLAH"); 
    } 
});*/ 
} 
    public String studentOutputString(String student){ 
     String s = student + "is printed."; 
     return s; 
} 

    public void actionPerformed(ActionEvent e) { 
     comboBox = (JComboBox) e.getSource(); 
     String selectedStudent = (String) comboBox.getSelectedItem(); 
     textField.setText(studentOutputString(selectedStudent)); 
} 

テキストフィールドには何も表示されません。私が間違っていることについて何か考えている?

私はそれを再フォーマットし、私の過去のスレッドに巻き込まれました。

+0

[SSCCE](http://sscce.org/) – Dave

+0

@Dave - 注意してください。さらに、私は答えられなかったいくつかの質問に対する答えを選んだ。前にいくつかの投稿を見たことがなかった。 – user963070

答えて

0

アクションリスナーを呼び出してTextFieldのテキストを設定するには、ComboBoxでアクションを生成する必要があります。コンボボックスでアイテムを選択してみてください

また、選択したアイテムの変更以外のイベント(選択前にイベントが生成されたなど)がある場合は、comboBox.getSelectedItem()がnullを返すことがあります。その場合、student + "is printed."studentOutputString()に電話すると、ヌルポインタ例外が発生します。

+0

私はコンボボックスの値を無駄に変更しようとしました。私は何をすべきかわかりません。 – user963070

+0

では、コンボボックスの値は_changing_されませんが、アプリケーションが実行されているときは_selecting_とコンボボックスの項目になります。 – Attila

+0

はい、そうです。 – user963070

関連する問題