Null Pointer Exception and Swing

advertisements

Hi I am trying to get the letter x to appear on lines 1-4 and the letter y to appear on lines 7-10. For some reason it works when I put else instead of else if so every line but 1-4 gets "y". It marks the else read and says to delete this token and says Null Pointer Exception and I get an error on line 26, the one with the frame.add

import java.awt.Color;
import java.awt.GridLayout;
import java.util.Random;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class ButtonGrid {
    JFrame frame=new JFrame();
    JButton[][] grid;
    public ButtonGrid(int width, int length){
        Random r=new Random();
        int w=r.nextInt(13-1)+1;
        frame.setLayout(new GridLayout(width,length));
        grid=new JButton[width][length];
        Scanner g = new Scanner(System.in);
        for(int y=0;y<length;y++){
            for(int x=0;x<width;x++){
                if (y < 4) {
                    grid[x][y]=new JButton("x");-I am trying to set lines 1-4 to x
                }
                else if (y>7){
                    grid[x][y]=new JButton("y");-I am trying to set lines 7-10 to y
                }
                frame.add(grid[x][y]);
                else{ "IT MARKS THIS AS WRONG"
                    grid[x][y]=new JButton(" ");
                }
            }
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);``
    }
    public static void main(String[] args) {
        new ButtonGrid(10,10);

    }
}

I think I am doing everything correctly just not sure why eclipse gives me these errors. Please Help! Eventually I'm going to be inputting on lines 7-10 but this test wasn't working. I am doing the board game Stratego in Swing if anybody knows how to help me.


To solve one of your problems: You can only have an else block immediately after an if block. You're getting an error because you've inserted the statement frame.add(grid[x][y]); in between your else if { ... } block and your else { ... } block.