Печать NullPointerException в массив Java-апплета - PullRequest
0 голосов
/ 11 декабря 2011

Две основные проблемы с этим. Один из самых последних блоков кода в нижней части этого раздела дает мне исключение NullPointerException. Я хочу, чтобы он добавлял * каждый раз, когда обнаруживает событие, происходящее в эту конкретную дату.

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

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Calendar extends Applet implements ActionListener{

/**
 * 
 */
private static final long serialVersionUID = 1L;
private Button next, last;
private Label month,showYear,sun,mon,tue,wed,thu,fri,sat;
private Label[] allDays= new Label[37];
private Label[] eventMarker = new Label[37]; 
private String[] months= {"January","February","March","April","May","June",
        "July","August","September","October","November","December"};
private String[] monthDays = {"31","29","31","30","31","30","31","31","30","31","30","31"};
private int current,year,dateHold,stringParse;
private final int MAX = 1000;//number of events
//arrays for data input from file
private int overallIndex = 0;
private String[] usrMonth= new String[MAX];
private String[] usrDay = new String[MAX];
private int[] usrYear = new int[MAX];
//private int[] usrTime = new int[MAX];
private String[] usrInfo = new String[MAX];
private TextField[] fields = new TextField[5];
private Label[] overFields = new Label[5];
private Button addApt ;


public void init(){
    setSize(1050,750);
    year = 2012;
    current = 0;//month in array
    next = new Button("Next");
    last = new Button("Last");
    month = new Label(months[current]);
    showYear = new Label("Year 2012");

    //day names on calendar
    sun = new Label("Sunday");
    mon = new Label("Monday");
    tue = new Label("Tuesday");
    wed = new Label("Wednesday");
    thu = new Label("Thursday");
    fri = new Label("Friday");
    sat = new Label("Saturday");
    //day numbers on calendar originally for January 2012
    String num;
    for(int i = 0; i < 37; i++){
        if(i > 30)
            allDays[i]=new Label(" ");
        else{
        num = "" + (i+1);
        allDays[i]=new Label(num);}
    }

    for(int i = 0; i < 37; i++){
        eventMarker[i] = new Label("|:");
    }

    addApt = new Button("Add Appointment");
    overFields[0] = new Label("Enter month by number.");
    overFields[1] = new Label("Enter the number date.");
    overFields[2] = new Label("Enter the year.");
    overFields[3] = new Label("Enter any information on appointment.");
    overFields[4] = new Label("Search appointments for key words here.");

    for (int i = 0; i < 5; i ++){
        fields[i] = new TextField("Dont forget to press Enter.",300);
    }


    //GUI add's

    //buttons
    add(next);
    add(last);
    add(addApt);
    //labels
    add(month);
    add(showYear);
    add(sun);
    add(mon);
    add(tue);
    add(wed);
    add(thu);
    add(fri);
    add(sat);
    //text fields and actionListener
    for(int i = 0; i < 5; i++){
        add(overFields[i]);
        add(fields[i]);
        fields[i].addActionListener(this);
    }

    for(int i = 0; i <37; i++)//Add array
        add(allDays[i]);


    //button listeners
    next.addActionListener(this);
    last.addActionListener(this);


}//end of init

public void paint(Graphics g){
    int first = 571;
    for (int i = 0; i < 6; i++){//Vertical lines
        g.drawLine(first, 75, first, 600);
        first += 71;
    }




    //day name positions
    sun.setBounds(510,75,40,10);
    mon.setBounds(580,75,40,10);
    tue.setBounds(650,75,40,10);
    wed.setBounds(710,75,40,10);
    thu.setBounds(790,75,40,10);
    fri.setBounds(860,75,40,10);
    sat.setBounds(930,75,40,10);

    //day number positions
    int second;





    first = 100;//horizontal line start and finish position 
    for (int i = 0; i < 7; i++){//horizontal lines
        if (i == 0)//indented on first line
        g.drawLine(525, first, 975, first);
        else 
            g.drawLine(500, first, 1000, first);

        first += 100;
    }

    for(int i = 0; i < 37; i++){//adding labels event marker
        add(eventMarker[i]);
    }



    first = 510;//position for event marker
    second = 125;//diddo
    for(int i = 0; i < 37; i++){//set position event marker
        for(int j = 0; j < 7; j++){//inner loop for a per week
            if((i+j) >= 37)//if index finishes, but loop still has days in week that would call out of bounds
                continue;
            eventMarker[i+j].setBounds(first,second,10,10);//added index's for specific day of week
            first+=71;

        }
        i+= 6;
        first = 510;
        second += 100;
    }

    last.setBounds(505,31,88,30);
    next.setBounds(895,31,88,30);
    month.setBounds(730,31,100,30);
    showYear.setBounds(800,31,100,30);
    addApt.addActionListener(this);
    //frame
    g.drawRect(0, 0, 500, 700);
    g.drawRect(500, 0, 500, 700);

    //text fields and labels bounds
    first = 120;
    second = 150;
    for(int i = 0; i < 5; i++){
        overFields[i].setBounds(first,second,100,20);
        second += 30;
        fields[i].setBounds(first, second, 300, 20);
        second += 50;
    }
    addApt.setBounds(300,600,100,30);

    repaint();

}//end of paint

public void repaint(){


    int first = 550;//date number position
    int second = 105;
    for(int i = 0; i < 37; i++){//Setting date number position
        for(int j = 0; j < 7; j++){//inner loop for a per week
            if((i+j) >= 37)//if index finishes, but loop still has days in week that would call out of bounds
                continue;
            allDays[i+j].setBounds(first,second,10,10);//added index's for specific day of week
            first+=71;

        }
        i+=6;
        //setting bounds
        second+=100;
        first=550;
    }
}

public void actionPerformed(ActionEvent evt){
    if (evt.getSource()==next){
        current++;
        if(current == 12){//resets to January
            current = 0;
            year++;
            String now="Year " + year;
            showYear.setText(now);


        }
        month.setText(months[current]);
        for (int i = 0; i < 37; i++){//setting proper day numbers
            if(allDays[i].getText().equals(monthDays[current==0 ? 11:current-1]))//so you don't access index -1
                dateHold=i +1;//for zero index of i
            dateHold%=7;//date left off at
        }

        //dateHold++;
        for(int j = 0; j < 37; j++)//erase dates
            allDays[j].setText("");

        for(int i = 0; i < 37; i++){//sets dates

            stringParse = Integer.parseInt(monthDays[current]);
            if(current==1 && (i+2) ==  stringParse && year%4!=0){//on the 28 of non leap years feb, print then break loop
                allDays[dateHold].setText("" + (i+1));
                break;
            }
            if((i+1) > stringParse)//without going over max per month
                continue;
            allDays[dateHold].setText("" + (i+1));
            dateHold++;
        }
        for(int i = 0; i < 37; i++){
            eventMarker[i].setText("|;");
        }

    }//end next evt

    if (evt.getSource()==last){//NOT CURRENTLY WORKING...
        current--;
        if(current == -1){//resets to February
            current = 11;
            year--;
            String now = "Year " +year;
            showYear.setText(now);
        }
        month.setText(months[current]);

        stringParse = Integer.parseInt(monthDays[current]);
        for (int i = 0; i < 7; i++){//check first week
            if(allDays[i].getText().equals("1")){
                dateHold =i;//plus then minus to fix index and next month
            }
        }
        for(int j = 0; j < 37; j++)//erase dates
            allDays[j].setText("");

        int something;//local number holder

        int countDown = stringParse;//local count down for reverse printing
        if(current ==1 && year%4!=0)//February fix
            countDown = 28;
        something = countDown - 1 + (dateHold);
        for (int i = 36; i >0; i--){//reverse date printing


            if(((36 -i)-dateHold)>stringParse)//if date over max
                continue;


            if(something < 0)
                continue;

            try{//kept reaching out of index here
            allDays[something].setText("" + (countDown));
            //System.out.println("i:" + i + "\ndateHold:" + dateHold + "\ncountDown:" + countDown);
            }
            catch(ArrayIndexOutOfBoundsException e){
                System.out.println("error i:" + i + "\ndateHold:" + dateHold + "\ncountDown:" + countDown);
            }
            countDown--;
            something--;
            if(countDown <= 0)
                break;
        }
        for(int i = 0; i < 37; i++){
            eventMarker[i].setText("|;");
        }

    }//end last evt

    String theDate;
    int numDate;
    if(evt.getSource() == fields[0]){
        theDate = fields[0].getText();

        try{
            numDate = Integer.parseInt(theDate);
            usrMonth[overallIndex] = months[(numDate-1)];
        }catch(NumberFormatException e){
            System.out.println("Error field[0]");
        }
        catch(ArrayIndexOutOfBoundsException e){}

    }//end of fields[0]

    if(evt.getSource() == fields[1]){
        theDate = fields[1].getText();
        try{
            numDate = Integer.parseInt(theDate);
            usrDay[overallIndex] = theDate;
        }catch(NumberFormatException e){System.out.println("Error field[1]");}
        catch(ArrayIndexOutOfBoundsException e){}
    }//end of fields[1]

    if(evt.getSource() == fields[2]){
        theDate = fields[2].getText();
        try{
            numDate = Integer.parseInt(theDate);
            usrYear[overallIndex] = numDate;
        }catch(NumberFormatException e){System.out.println("Error field[2]");}
        catch(ArrayIndexOutOfBoundsException e){}
    }//end of fields[2]

    if(evt.getSource() == fields[3]){
        theDate = fields[3].getText();
        usrInfo[overallIndex] = theDate;
    }

    if(evt.getSource() == addApt){
        if(usrDay[overallIndex] != null && usrMonth[overallIndex] != null){



            theDate = fields[1].getText();
            try{
                numDate = Integer.parseInt(theDate);
                usrDay[overallIndex] = theDate;
            }catch(NumberFormatException e){System.out.println("Error field[1]");}
            catch(ArrayIndexOutOfBoundsException e){}
            theDate = fields[2].getText();
            try{
                numDate = Integer.parseInt(theDate);
                usrYear[overallIndex] = numDate;
            }catch(NumberFormatException e){System.out.println("Error field[2]");}
            catch(ArrayIndexOutOfBoundsException e){}
            theDate = fields[3].getText();
            usrInfo[overallIndex] = theDate;




            System.out.println("Appointment Added\n" + (String) usrDay[overallIndex] +  "\n" + usrMonth[overallIndex] + "\n" + usrInfo[overallIndex] + "\n" +usrYear[overallIndex]);

            checkEvent();
            repaint();
            overallIndex++;//ONLY PLACE THIS CAN HAPPEN
            for (int i = 0; i < 5; i++)
                fields[i].setText("Dont forget to press Enter.");
        }
    }

}//end of action performed

public void checkEvent(){
    try{for(int i = 0; i < MAX; i++){//checking for events
        if(usrMonth[i].equals(months[current]) &&
                usrYear[i] == year){
            for(int j = 0; j < 37; j++){
                if(allDays[j].getText().equals(usrDay[i])){
                    String hold = eventMarker[j].getText();
                    hold += "*";
                    eventMarker[j].setText(hold);

                }
            }
        }
    }}
    catch(NullPointerException e){System.out.println("Null really");}
}


}

1 Ответ

0 голосов
/ 11 декабря 2011

Возможные нулевые значения:

usrMonth[i]
allDays[j]
allDays[j].getText()
eventMarker[j]

В какой строке вы получаете исключение?

...