2013-02-22 2 views
0

У меня есть две программы, каждая из которых создает другую вкладку в апплете, где пользователь может вводить типы домашних животных на одной вкладке, а затем выбирать и добавлять или удалять типы домашних животных список на другой вкладке. Я думал, что мне удалось решить все проблемы, но оба теперь дают мне java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Я не могу понять, почему я получаю эти ошибки. Вот два кода.Два случая непроверенных или небезопасных операций с JLists и векторами

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.util.*; 

public class CreatePanel extends JPanel 
{ 
    private Vector petList; //Instantiation of variables. To save space, multiple variables 
    private JButton button1; //were instantiated at a time when possible, such as the panels. 
    private SelectPanel sPanel; 
    private JLabel text1, redText; 
    private JTextField petInput; 
    private JTextArea petsIn; 
    private Panel wPanel, alertPanel, petPanel, createPanel; 



public CreatePanel(Vector petList, SelectPanel sPanel) 
    { 
    this.petList = petList; 
    this.sPanel = sPanel; 


    // orgranize components here 
    // here is an example 
    setLayout(new GridLayout(1,2)); 

    text1 = new JLabel("Enter a Pet Type"); //Creation of the visible portions of the applet 
    petInput = new JTextField(); 
    button1 = new JButton("Create a Pet"); 
    petsIn = new JTextArea("No Pet"); 
    wPanel = new Panel(); //Panels have to be used to ensure the porper layout of the 
    petPanel = new Panel(); //applet so it conforms to assignment specifications 
    createPanel = new Panel(); //making for a pretty panel, but some very ugly code 
    alertPanel = new Panel(); 
    alertPanel.setLayout(new GridLayout(1,2)); 
    createPanel.setLayout(new GridLayout(2,3)); 
    petPanel.setLayout(new GridLayout(1,2)); //Each panel has its own layout, making for layouts 
    wPanel.setLayout(new GridLayout(3,1)); //in layouts to get everything looking correct. 
    button1.addActionListener(new ButtonListener()); //adds the listener to the button 

    add(wPanel); 
    wPanel.add(alertPanel); 
    alertPanel.add(redText); 
    wPanel.add(petPanel); 
    petPanel.add(text1); 
    petPanel.add(petInput); 
    wPanel.add(createPanel); 
    createPanel.add(new JLabel()); 
    createPanel.add(button1); 
    createPanel.add(new JLabel()); //Have to create several blank labels to get position of 
    createPanel.add(new JLabel()); //the create pet button to be positioned correctly. 
    createPanel.add(new JLabel()); 
    createPanel.add(new JLabel()); 
    add(petsIn); 


    } 

    private class ButtonListener implements ActionListener 
    { 
    public void actionPerformed(ActionEvent event) 
    { 
     String inputPet = petInput.getText(); //Gets the user input pet 
     boolean checker = false; // A boolean check type so pets can't be added repeatedly 

     for (int p = 0; p < petList.size(); p++){ //Runs a check through the petList vector 
      if (inputPet.equalsIgnoreCase((String) petList.get(p))){ //If a pet already exists (ignoring case) then the check is set to true 
       checker = true; //for a later if loop to inform the user. 
       break; 
      } 
     } 


     if(inputPet.equals("")){ 
      redText.setText("Please enter a pet type."); 
      redText.setForeground(Color.red); 
     } else if (checker == true){ 
      redText.setText("The pet type already exists."); 
      redText.setForeground(Color.red); 
     } else { 
      petList.add(inputPet); 
      String addedPets = (String) petList.get(0); 
      for(int i = 1; i < petList.size(); i++){ 
       addedPets += "\n" + (String) petList.get(i); 
      } 
      redText.setText("Pet type added."); 
      redText.setForeground(Color.red); 
      petsIn.setText(addedPets); 
      sPanel.updateUI(); 
     } 
     redText.setText(""); 

    } //end of actionPerformed method 
    } //end of ButtonListener class 

} //end of CreatePanel class 

и

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.*; 
import java.util.*; 

public class SelectPanel extends JPanel 
{ 
    private Vector petList, selectList; 
    private Panel bPanel, nPanel; 
    private JLabel sPets, aPets, nPets; 
    private int numPets = 0; 
    private JButton addPet, remove; 
    private JList petsAvail, petTypes; 
    private JScrollPane sPane, sPane2; 

    public SelectPanel(Vector petList) 
    { 
     this.petList = petList; 

     this.setLayout(new BorderLayout()); 

     bPanel = new Panel(); 
     nPanel = new Panel(); 
     nPanel.setLayout(new GridLayout(1,2)); 
     bPanel.setLayout(new GridLayout(2,1)); 

     petTypes = new JList(petList); 
     petTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
     sPane = new JScrollPane(petTypes); 
     petList.add(0, "Available pet(s)"); 

     selectList = new Vector(); 
     petsAvail = new JList(selectList); 
     petsAvail.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
     sPane2 = new JScrollPane(petsAvail); 
     selectList.add(0, "Selected pet(s)"); 

     aPets = new JLabel("Available pet(s)"); 
     nPets = new JLabel("Selected pet(s)"); 
     nPets = new JLabel("The number of selected pets:" + numPets); 
     addPet = new JButton("Add"); 
     remove = new JButton("Remove"); 

     add(petsAvail, BorderLayout.EAST); 
     add(petTypes, BorderLayout.WEST); 
     add(nPanel, BorderLayout.SOUTH); 
     nPanel.add(nPets); 
     add(bPanel, BorderLayout.CENTER); 
     bPanel.add(addPet); 
     bPanel.add(remove); 

     addPet.addActionListener(new ButtonListener()); 
     remove.addActionListener(new ButtonListener()); 


    // orgranize components for the panel 
    } 

public void updatePetList() 
    { 
     petTypes.updateUI(); 
     petsAvail.updateUI(); 
     //This method can refresh the appearance of the list of pets 
     //by calling updateUI() method for the JList. 
     //It can be called from the CreatePanel class whenever a new pet type 
     //is added to the vector and the JList appearence needs to be refreshed. 
    } 

private class ButtonListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      Object which = event.getSource(); 

      if(which == addPet){ 
       for (int p = 1; p < selectList.size(); p++){ 
        boolean check = false; 

        if(selectList.contains(petTypes.getSelectedValue())){ 
         check = true; 
         break; 
        } else if(check == false){ 
         selectList.addElement(petTypes.getSelectedValue()); 
         petsAvail.updateUI(); 
         numPets++; 
        } 
       } 
      } else if (which == remove){ 
       selectList.removeElement(petsAvail.getSelectedValue()); 
       updatePetList(); 
       numPets--; 
      } 



      //When the added button is pushed, the selected pet 
      //should be added to the right list and the number of 
      //selected pets is incremented by 1. 
      //When the remove button is pushed, the selected pet 
      //should be removed from the right list and the number of 
      //selected pets is decremented by 1. 
      // 
      //Be careful for the cases when no item has been selected. 
     } 
    } //end of ButtonListener class 

} //end of SelectPanel class 

Любое понимание, как на причину этих ошибок и что делать о них будут с благодарностью приняты.

ответ

1

Вы получаете это предупреждение, потому что используете общий класс без указания общего типа. Похоже, что ваш вектор petList должен быть вектором строк. Ваша декларация petList должна выглядеть

private Vector<String> petList 

и где-то позже ...

petList = new Vector<String>() 

Это предупреждение предназначено, чтобы помочь вам понять, что ваш код не может вести себя, как ожидается, во время выполнения, если Вы начинаете смешивания типов (обычно быть случайным) внутри вашего вектора. Вы можете технически добавлять несколько типов объектов в свой вектор petList, даже если вам действительно нужны строки. Ничто не мешает вам добавлять в ваш вектор целые числа, другие классы или даже больше векторов. Иногда это делается специально программистом, но большую часть времени вы действительно хотите, чтобы один тип объекта использовался в вашем общем классе (в этом случае вектор). Указав тип объектов, которые будут помещены в ваш вектор, компилятор может помочь вам поймать это случайное смешивание типов (например, если вы попытались поместить целое число в вектор petList). Гораздо легче решить эти проблемы во время компиляции, а не пытаться выяснить, что пошло не так во время выполнения.

Читайте здесь, чтобы узнать больше о воспроизведенных в Java: http://docs.oracle.com/javase/tutorial/java/generics/

+0

Добавление все векторные использования (в том числе в 3-файл) избавились от предупреждений на всех файлов, кроме файла выберите панель – eevpix

+0

Oh черт возьми, я буду казаться глупым. Я забыл создать экземпляр JLabel «redText» в методе createPanel. Вот почему он не работает. – eevpix

Смежные вопросы