Java JComboBox错误
我试图从Liang编写的“Java编程入门第9版”中编译以下程序。我在以下关于JComboBox的示例中发现一个错误:Java JComboBox错误,java,swing,jcombobox,Java,Swing,Jcombobox,我试图从Liang编写的“Java编程入门第9版”中编译以下程序。我在以下关于JComboBox的示例中发现一个错误: import javax.swing.*; public class GUIComponents { public static void main (String[] args) { JButton jbtOK = new JButton ("OK");
import javax.swing.*;
public class GUIComponents
{
public static void main (String[] args)
{
JButton jbtOK = new JButton ("OK"); // Creates a button with test OK
JButton jbtCancel = new JButton ("Cancel"); // Creats a cancel button
JLabel jlblName = new JLabel ("Enter your name: "); // Creates a label with the respective text
JTextField jtfName = new JTextField ("Type Name Here"); // Creates a text field with the respective text
JCheckBox jchkBold = new JCheckBox ("Bold"); // Creates a check boc wth the text bold
JCheckBox jchkItalic = new JCheckBox ("Italic");
JRadioButton jrbYellow = new JRadioButton ("Yellow"); // Creates a radio button with text Yellow
JRadioButton jrbRed = new JRadioButton ("Red"); // Creates a radio Button with text Red
**JComboBox jcboColor = new JComboBox (new String[] {"Freshman", "Sophomore", "Junior", "Senior"});**
JPanel panel = new JPanel (); // Creates a panel to group components
panel.add (jbtOK); // Add the OK button to the panel
panel.add (jbtCancel); // Add the Cancel button to the panel
panel.add (jlblName); // Add the lable to the panel
panel.add (jtfName);
panel.add (jchkBold);
panel.add (jchkItalic);
panel.add (jrbRed);
panel.add (jrbYellow);
panel.add (jcboColor);
JFrame frame = new JFrame ();
frame.add (panel);
frame.setTitle ("Show GUI Components");
frame.setSize (450,100);
frame.setLocation (200, 100);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setVisible (true);
}
}
产生的错误是:
warning: [unchecked] unchecked call to JComboBox(E[]) as a member of the raw type JComboBox
JcomboBox jcboColor = new JComboBox(new String[] {"Freshman", "Sophomore", "Junior", "Senior"});
Where E is a time-variable:
E extends Object Declared in class JComboBox
这是一个警告而不是错误。您缺少Java 1.7中引入的预期泛型类型。没有它,每次从
ComboBoxModel
将字符串
类型添加到声明中以匹配模型数据
JComboBox<String> jcboColor = new JComboBox<>(new String[] { ... });
JComboBox jcboColor=newjcombobox(新字符串[]{…});
阅读这篇来自泛型常见问题解答的有趣文章,到目前为止,Oracle的Swing教程中包含以下内容: 运行此命令会导致以下行抛出此警告:
JComboBox cb = new JComboBox(comboBoxItems);
可能是因为代码自2008年以来就没有更新过?此解决方案帮助我清理了警告并顺利编译,因此值得称赞。这是一个警告,不是错误,因为
imageComboBox=new JComboBox(names);
再次运行该程序,它将正常工作
您确定有错误吗?听起来像是关于类型安全的警告。如果确实是这样,那么您可以使用@SuppressWarnings(“未选中”),如下所述: