问题描述
packagelistdemo;importjava.awt.BorderLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.*;publicclasscomboboxdemo{privateJLabellabel;publicvoidcreateui(){JFrameframe=newJFrame("组合框示例程序");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);String[]items={"选项一","选项二","选项三"};JComboBoxcombobox=newJComboBox(items);combobox.addActionListener(newComboBoxAction());label=newJLabel();frame.getContentPane().add(combobox,BorderLayout.NORTH);frame.getContentPane().add(label,BorderLayout.SOUTH);frame.setBounds(200,200,250,120);frame.setVisible(true);}classComboBoxActionimplementsActionListener{publicvoidactionPerformed(ActionEventevent){JComboBoxbox=(JComboBox)event.getSource();label.setText(box.getSelectedItem()+"被选择");}}publicstaticvoidmain(String[]args){comboboxdemoexample=newcomboboxdemo();example.createui();}}编译时提示:Themethodadd(String,Component)inthetypeContainerisnotapplicableforthearguments(JComboBox,String),add添加方法参数不对,怎么修改?
解决方案
解决方案二:
参数反了,frame.getContentPane().add(combobox,BorderLayout.NORTH);改为frame.getContentPane().add(BorderLayout.NORTH,combobox);
解决方案三:
建议看下API:http://download.oracle.com/technetwork/java/javase/6/docs/zh/api/java/awt/Container.html
解决方案四:
不行,把方法frame.getContentPane().add(BorderLayout.NORTH,combobox);修改了还是提示错误,是不是swing组件不够完整?按照提示参数combobox的类型是JPane,不过combobox类型是JComboBox,没有办法转换?
解决方案五:
add(Componentcomp,Objectconstraints),getContentPane()的add要求的参数类型是JPane
解决方案六:
说错了,frame.getContentPane().add(BorderLayout.NORTH,combobox);提示是quickfixavailable:Changetypeof'combobox'to'Component'
解决方案七:
楼主代码在eclipse可以运行呀。你的JDK版本是多少?
解决方案八:
运行结果