0

我有一个问题,我有一个组合框,该组合框会导致在 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));
}

textField 中没有显示任何内容。知道我做错了什么吗?

我重新格式化它并赶上了我过去的线程。

4

1 回答 1

0

您需要在 ComboBox 上生成一个动作,以便调用动作侦听器并设置 TextField 的文本。尝试在 ComboBox 中选择一个项目

此外,comboBox.getSelectedItem()如果除了所选项目的更改之外还有其他事件(例如,在进行选择之前生成了一个事件),则可能返回 null。在这种情况下,您对student + "is printed."inside的调用studentOutputString()将引发空指针异常

于 2012-04-11T21:01:58.317 回答