-1

我有以下代码,但我不断收到错误。

void 是变量 itemStateChanged 的​​无效类型 这是错误消息,但是当我取出 void 时出现语法错误。

任何人都可以修复代码。

final JComboBox combobox = new JComboBox(procedurelist);
combobox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        procedure = (String) combobox.getSelectedItem();

        private void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED) {
                if("Focus".equals(e.getItem())) {
                    textField_9.requestFocus();
                }
            }
        }
    }

});
combobox.setBounds(68, 216, 86, 20);
contentPane.add(combobox);
4

2 回答 2

1

您在方法中声明方法,这是无法做到的。

根据您要执行的操作,您实际上并不需要它...

final JComboBox combobox = new JComboBox(procedurelist);
combobox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        procedure = (String) combobox.getSelectedItem();

        if("Focus".equals(procedure)) {
            // Set text??
            textField_9.requestFocusInWindow();
            // Select all..
        }
    }

});
// Bad idea, learn to use layout managers
//combobox.setBounds(68, 216, 86, 20);
contentPane.add(combobox);
于 2013-04-30T09:53:40.973 回答
1
public void actionPerformed(ActionEvent event) {   //Method declaration
    procedure = (String) combobox.getSelectedItem();

    private void itemStateChanged(ItemEvent e) {  //Another Method declaration
        if(e.getStateChange() == ItemEvent.SELECTED) {
            if("Focus".equals(e.getItem())) {
                textField_9.requestFocus();
            }
        }
    }
}

您在另一个方法中声明一个方法。Java 语法不允许这样做。如果您尝试监视ComboBox使用中项目的状态更改ItemListener

final JComboBox combobox = new JComboBox(procedurelist);
combobox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        procedure = (String) combobox.getSelectedItem();
    }
});

combobox.addItemListener(new ItemListener(){

        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED) {
                if("Focus".equals(e.getItem())) {
                    textField_9.requestFocus();
                }
            }
        }
});
于 2013-04-30T09:48:35.570 回答