Alright so basically what I'm trying to do is create a 16x16 square board of tiles (256 total) and when I run the program I need it to set up the tiles randomly into the following colors
39 yellow tiles
46 red tiles
34 blue tiles
52 green tiles
41 magenta tiles
44 cyan tiles
When I run the code, I'm getting a null pointer attiles[i].setBackground(Color.YELLOW);
Heres the GUI class
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; public class GameBoard extends JFrame{ Tile[][] myTiles; private int numRows = 16, numCols = 16; //private MyEventHandler eh = new MyEventHandler(); public static void main(String[] args) { new GameBoard(); } public GameBoard() { myTiles = new Tile[numRows][numCols]; setSize(800,800); Container c = getContentPane(); c.setLayout(new BorderLayout()); setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("Random Colors"); JPanel tilePanel = buildTilePanel(); c.add(tilePanel, BorderLayout.CENTER); setVisible(true); } private JPanel buildTilePanel() { JPanel tilePanel = new JPanel(); tilePanel.setBackground(Color.BLACK); tilePanel.setPreferredSize(new Dimension(800, 800)); tilePanel.setLayout(new GridLayout(numRows, numCols)); for (int i = 0; i < myTiles.length; i++) for (int j = 0; j < myTiles[0].length; j++) { myTiles[i][j] = new Tile(); myTiles[i][j].setColors(); myTiles[i][j].shuffle(); //myTiles[i][j].addActionListener(eh); tilePanel.add(myTiles[i][j]); } return tilePanel; } }
and heres the tiles class
import java.awt.Color; import java.awt.Dimension; import javax.swing.JButton; public class Tile extends JButton{ private Tile[] tiles = new Tile[256]; public Tile() { setPreferredSize(new Dimension(10, 10)); } public void setColors() { for(int i = 0; i < 39; i++){ tiles[i].setBackground(Color.YELLOW); paintImmediately(0, 0, getWidth(), getHeight()); } for(int i = 39; i < 85; i++){ tiles[i].setBackground(Color.RED); paintImmediately(0, 0, getWidth(), getHeight()); } for(int i = 85; i < 119; i++){ tiles[i].setBackground(Color.BLUE); paintImmediately(0, 0, getWidth(), getHeight()); } for(int i = 119; i < 171; i++){ tiles[i.]setBackground(Color.GREEN); paintImmediately(0, 0, getWidth(), getHeight()); } for(int i = 171; i < 212; i++){ tiles[i].setBackground(Color.MAGENTA); paintImmediately(0, 0, getWidth(), getHeight()); } for(int i = 212; i < 256; i++){ tiles[i].setBackground(Color.CYAN); paintImmediately(0, 0, getWidth(), getHeight()); } } public void shuffle() { int r = tiles.length; for(int i = 0; i < tiles.length; i++){ Tile t = tiles[i]; tiles[i] = tiles[r-1]; tiles[r-1] = t; } } }