2015-11-22 4 views
0

Это моя первая программа GUI, и я не могу понять, почему Im получает эту ошибку. Я настраивал свой интерфейс actionListener как внутренний класс в своей основной. Я попытался поместить весь код, ссылающийся на класс после класса, а также без везения, основанного на некоторых других сообщениях, которые я прочитал.не может найти ссылку на переменную actionlistener

Assig4.java:57: error: cannot find symbol 
     ActionListener listener2 = new MListener(); 
             ^
    symbol: class MListener 
    location: class Assig4  
    LINE 57 FOR REFERENCE: ActionListener listener2 = new MListener(); 
//import section 
import java.awt.*; 
import java.awt.event.*; 
import java.io.File; 
import java.io.IOException; 
import java.lang.reflect.Array; 
import java.util.ArrayList; 
import java.util.*; 
import javax.swing.*; 


public class Assig4 { 


    public static void main (String [] args) throws IOException 
    { 

     /* variables */ 

     String ballotsFile = args[0]; // gets the file name from command line 
     JFrame theWindow; //assign variable name for main window 
     ArrayList <Ballot> ballotsAr = new ArrayList<>(); //creates array for jpanel ballot objects 

     int numBallots=0; 
     int counter = 0; //to count each file read in loop 
     JButton login, submitVote; 
     //voter variables 
     ArrayList <Integer> voterIdList = new ArrayList<>(); 
     ArrayList <String> voterNames = new ArrayList<>(); 
     ArrayList <Boolean> voterVoted = new ArrayList<>(); 

     /*create window*/ 

     theWindow = new JFrame ("Voting E Machine"); 
     theWindow.setLayout(new FlowLayout()); 

     /* read in ballot info and create ballot objects*/ 

     numBallots = readInBallotFile(ballotsFile, numBallots, ballotsAr); 

     /*read in data from voter file*/ 

     try { 
      // method that accesses the file 
      readInVoterFile(voterIdList, voterNames, voterVoted); 
     } 
     catch (Exception e) 
     {} 

     /*create action listener object */ 
     ActionListener listener2 = new MListener(); 

     /*add Ballot panels*/ 
     addPanels(theWindow, ballotsAr); 

     /*add local components*/ 
     submitVote = new JButton("Submit Vote(s)"); 
     submitVote.setEnabled(false); 
     submitVote.addActionListener(listener2); 
     login = new JButton("Login"); 
     login.addActionListener(listener2); 
     theWindow.add(submitVote); 
     theWindow.add(login); 

     /*pack and set window to visible*/ 

     theWindow.pack(); 
     theWindow.setVisible(true); 

     /*actionListener class to handle login and vote submissions*/ 

     class MListenter implements ActionListener 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       //if submitVote button is clicked 
       if (ae.getSource() == submitVote) 
       { 
        //tally results 
        //update voter file local variables including false to true for voted 
        //write data to temp file 
        //delete original file 
        //change temp file name to previous file name 
       } 

       //if login button is clicked 
       if (ae.getSource() == login) 
       { 

        String userEntryIdString; 
        int userEntryId; 
        boolean registered=false; 

        do { 
         userEntryIdString = JOptionPane.showInputDialog("Enter your voter ID number: "); 
         userEntryId = Integer.parseInt(userEntryIdString); 
         //check id number against registered citizens 
         for (int v =0; v < voterIdList.size(); v++) 
         { 
          if (userEntryId == voterIdList.get(v)) 
          { 
           registered = true; 
          } 
         } // end of loop to check id against id list 

         if (registered) 
         { 
          //enable buttons 
          for (int j = 0; j<ballotsAr.size(); j++) 
          { 
           ballotsAr.get(j).enableCandidateButtons(); 
          } 
          submitVote.setEnabled(true); 
         } 

         else if (!registered) 
          System.out.println("Invalid ID number. Please try again. "); 
        } while (!registered); 
       } //end of if login button is clicked 
      } //end of action performed method 

     }// end of actionlistener 

    } //end of main 

    public static int readInBallotFile(String ballotsFile, int numBallots, ArrayList<Ballot> ballotsAr) throws IOException 
    { 
     int counter = 0; 
     //objects - open and setup scanner for file 
     File myfile = new File (ballotsFile); 
     Scanner textScan = new Scanner(myfile); // reads in date from text file 
     numBallots = Integer.parseInt(textScan.nextLine()); //read in first line (number of ballots) and parse to int 
     while (textScan.hasNextLine()) //one ballot's data for each loop 
     { 

      //read in each ballot's info 
      //take the first line as a string 
      String [] tempStr = textScan.nextLine().split(":"); 
      //parse line into proper data values 
      int tempId = Integer.parseInt(tempStr[0]); //take first value for id 
      String tempCategory = tempStr[1]; // take second value as category type 
      String [] tempCandidates = tempStr[2].split(","); // takes the arbitrary number of candidates and splits into separate string variables 

      //create ballot object 
      ballotsAr.add(new Ballot(tempId,tempCategory,tempCandidates)); 
      counter++; //adds counter to while loop 
     } // end of loop to read in ballot text file contents 
     textScan.close(); //closes ballots.txt file 
     return numBallots; 
    } //end of read in ballot file method 

    public static void addPanels(JFrame theWindow, ArrayList <Ballot> ballotsAr) 
    { 
     for (int i =0; i<ballotsAr.size();i++) 
     { 
      theWindow.add(ballotsAr.get(i)); 
     } 
    } 

    public static void readInVoterFile(ArrayList <Integer> _voterIdList, ArrayList <String> _voterNames, ArrayList <Boolean> _voterVoted) throws IOException 
    { 
     int counter = 0; 
     //objects - open and setup scanner for file 
     File myfile = new File ("voters.txt"); 
     Scanner textScan = new Scanner(myfile); // reads in date from text file 
     while (textScan.hasNextLine()) //one voter's data for each loop 
     { 
      //take the first line as a string 
      String [] tempStr = textScan.nextLine().split(":"); 
      //parse line into proper data values 
      _voterIdList.add(Integer.parseInt(tempStr[0])); //take first value for voter id 
      _voterNames.add(tempStr[1]); // take second value as voter name 
      _voterVoted.add(Boolean.parseBoolean(tempStr[2])); 
      counter++; //adds counter to while loop 
     } // end of loop to read in voter text file contents 
     textScan.close(); //closes ballots.txt file 
    } // end of voter read in method 

} // end of class 
+0

Постарайтесь установить свое действие. Определение прослушивателя вне вашего метода, но все же внутри вашего класса. –

+0

Существует ли 'MListener'? – SLaks

+0

Пробовал это, но тогда ни одна из моих переменных не будет работать в классе Actionlistener – robotscantdie

ответ

1

опечатка один из них.

ActionListener listener2 = new MListener(); 

class MListenter implements ActionListener 

обратите внимание на дополнительное «t» в названии класса.

+0

Все еще не работает. Хороший улов, хотя! Спасибо. – robotscantdie

+0

Определите свой класс ближе к вершине main(), прежде чем ссылаться на него. –

+0

Спасибо Kiltos - он работает сейчас! – robotscantdie

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

  • Нет связанных вопросов^_^