.java使用未经检查和不安全的操作

时间:2014-09-14 11:56:58

标签: java swing warnings unsafe unchecked

这是我的java代码:

import javax.swing.*;

public class Employee1 extends JFrame {

    JPanel panel;
    JLabel l1;
    JList list;

    public Employee1() {
        super("Employee Details");
        panel = new JPanel();
        l1 = new JLabel("City : ");
        String cities[] = {"Mumbai", "Delhi", "Madras"};
        list = new JList(cities);
        panel.add(l1);
        panel.add(list);
        getContentPane().add(panel);
        setSize(400, 400);
        setVisible(true);
    }

    public static void main(String args[]) {
        Employee1 obj = new Employee1();
    }
}

这段代码告诉我警告.java使用未经检查和不安全的操作。我有考试,所以请帮助我完成考试

1 个答案:

答案 0 :(得分:3)

您应该为JList使用类型参数,因为这是一个泛型错误,JList支持genercis。

变化:

JList listJList<String> list
 和list = new JList(cities)list = new JList<>(cities)

public class Employee1 extends JFrame {
    private final JPanel panel;
    private final JLabel l1;
    private final JList<String> list;    // <--- first change

    public Employee1() {
        super("Employee Details");

        final String[] cities = {"Mumbai", "Delhi", "Madras"};

        panel = new JPanel();
        l1    = new JLabel("City : ");
        list  = new JList<>(cities);     // <--- second change

        panel.add(l1);
        panel.add(list);
        getContentPane().add(panel);

        setSize(400, 400);
        setVisible(true);
    }    
}

有关此主题的信息和示例,请参阅Lesson: Generics