Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Random Colors Problem

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Random Colors Problem

    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 it sets the entire board to CYAN. I understand why it does that because it's the last for loop in my code but I have no idea how to fix it.

    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++){
    			setBackground(Color.YELLOW);
    			paintImmediately(0, 0, getWidth(), getHeight());
     
    		}
     
    		for(int i = 39; i < 85; i++){
    			setBackground(Color.RED);
    			paintImmediately(0, 0, getWidth(), getHeight());
    		}
     
    		for(int i = 85; i < 119; i++){
    			setBackground(Color.BLUE);
    			paintImmediately(0, 0, getWidth(), getHeight());
    		}
     
    		for(int i = 119; i < 171; i++){
    			setBackground(Color.GREEN);
    			paintImmediately(0, 0, getWidth(), getHeight());
    		}
     
    		for(int i = 171; i < 212; i++){
    			setBackground(Color.MAGENTA);
    			paintImmediately(0, 0, getWidth(), getHeight());
    		}
     
    		for(int i = 212; i < 256; 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;
    		}
    	}
    }

    I've also tried adding tiles[i]. in front of setBackground but it threw a nullpointer so I'm just stuck..Any help is greatly appreciated. Thanks!
    Last edited by captain; February 20th, 2012 at 08:58 PM.


  2. #2
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Random Colors Problem

    Duplicate Post.

  3. #3
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: Random Colors Problem

    Places to look, Creating tiles, Inserting tiles, displaying tiles.

    Here is a few ways to check,
    Write a quick method that just returns the name of the color that tile is.
    When you create a tile, immediately ask it what color it is.
    Then insert it, then access where you inserted it, and ask it what color it is.
    I am going to look at the code now to see if I can spot it.

  4. #4
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: Random Colors Problem

    I don't know much about GUI but I think I see a problem.

    public void setColors() {

    your code goes through 256 for loops, so that increments desirably however,
    each time placing it over the exact same location unless paintImmediately parameters "getWidth()" & "getHeight()" increment.
    (And getters methods should never do this!)
    Thus each object in your array is painted 256 times always ending in cyan.

    Before I tell you how to fix it, first consider what is the job of the method setColors.(seriously... take 30 seconds )


    myTiles[i][j].setColors();

    This method call wants to take a specific tile (located somewhere already in your array) and color it.
    nothing illegal about this, but there is a contradiction in your ideas.
    The method code on the other-hand looks like it wants an array to fill all on its own(almost)

    you can either keep the tiles accessing the method one at a time and then change the method to some how keep track of what color to put in this one
    (use if statements instead of for loops)

    or have the method work on the entire array. (this is a little more work for your current code, but I feel is more proper)
    Pass the method the entire array, and change your for loops to if statements, then wrap them in 1 for loop that starts at i and goes through to the 256.

    Hope this helps,
    Jonathan


    }

  5. #5
    Junior Member
    Join Date
    Feb 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random Colors Problem

    Quote Originally Posted by JonLane View Post
    I don't know much about GUI but I think I see a problem.

    public void setColors() {

    your code goes through 256 for loops, so that increments desirably however,
    each time placing it over the exact same location unless paintImmediately parameters "getWidth()" & "getHeight()" increment.
    (And getters methods should never do this!)
    Thus each object in your array is painted 256 times always ending in cyan.

    Before I tell you how to fix it, first consider what is the job of the method setColors.(seriously... take 30 seconds )


    myTiles[i][j].setColors();

    This method call wants to take a specific tile (located somewhere already in your array) and color it.
    nothing illegal about this, but there is a contradiction in your ideas.
    The method code on the other-hand looks like it wants an array to fill all on its own(almost)

    you can either keep the tiles accessing the method one at a time and then change the method to some how keep track of what color to put in this one
    (use if statements instead of for loops)

    or have the method work on the entire array. (this is a little more work for your current code, but I feel is more proper)
    Pass the method the entire array, and change your for loops to if statements, then wrap them in 1 for loop that starts at i and goes through to the 256.

    Hope this helps,
    Jonathan


    }
    so you're basically saying something like this
    public void setColor() {
    		for(int i = 0; i < tiles.length; i++)
    			if(tiles[i] == null){
    				setBackground(Color.YELLOW);
    				paintImmediately(0, 0, getWidth(), getHeight());
    			}

    but obviously I need some kind of code to limit yellow to be set to only 39 tiles. how would I go about doing that?

    edit: or maybe something like this?
    public void setColor() {
    		tiles = new Tile[numRows];
    		for(int numRows = 0; numRows < tiles.length; numRows++)
    			if(numRows < 39){
    				setBackground(Color.YELLOW);
    				paintImmediately(0, 0, getWidth(), getHeight());
    			}
     
     
    	}
    Last edited by captain; February 21st, 2012 at 01:26 PM.

  6. #6
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: Random Colors Problem

    Quote Originally Posted by captain View Post
    edit: or maybe something like this?
    public void setColor() {
    		tiles = new Tile[numRows];
    		for(int numRows = 0; numRows < tiles.length; numRows++)
    			if(numRows < 39){
    				setBackground(Color.YELLOW);
    				paintImmediately(0, 0, getWidth(), getHeight());
    			}
     
    	}
    I assume the end product you want to be a 2d array. The current method structure will work for a 1d array.

    but getting to your new code,
    when you call: myTiles[i][j].setColors();

    you are using an object reference to access the method, this means your method already knows exactly which tile you want it to fill.
    (not sure if that is needed, because I have no idea how "setBackground(Color.YELLOW);" works. But if it does indeed fill something then no need to change anything.)

    All you need to do is write your method to choose what color you want, then to fill it with that color.

    Something like:
    public void setColor(int chooser) {
    		for(int idx = 0; idx < chooser; idx++)
    			if(idx < 39){
    				setBackground(Color.YELLOW);
    			}
    			else if(idx < ????){
    				setBackground(Color.????);
    			}
    			else {
    				setBackground(Color.????);
    			}
     			paintImmediately(0, 0, getWidth(), getHeight()); //NOTE: this can be outside the if statements!
    	}

    so I have added a parameter your method requires, now you have to consider how to get that to be the right number

    when you call: myTiles[i][j].setColors( //TODO );

    use i and j to create a non repeating sequence from 1 to 256 or 0 to 255 if that is easier.
    This sequence represents the unique ID of the current tile.

    Also, I am interested in using your project to learn more about GUI's. If you didn't mind posting the entire thing.(before or after it compiles) I would like to play around with some things for my own understanding.

    Thanks,
    Jonathan
    Last edited by JonLane; February 21st, 2012 at 05:59 PM. Reason: realized error in responce.

  7. #7
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Random Colors Problem

    One thing I would like to suggest is to think about your classes. You have a GameBoard and you have a Tile class. When you think about what a game board is, it is a collection of tiles. You have that here
    public class GameBoard extends JFrame{
        Tile[][] myTiles; //<---here
     
    }

    myTiles is a collection of tiles. But then you also have a seperate collection in the Tiles Class itself.
    public class Tile extends JButton{
     
    	private Tile[] tiles = new Tile[256]; //<--here

    You do not really need both. I suggest keeping Tile[][] myTiles; in your GameBoard and eliminating the tiles in your Tile class.

    Also, another thing you may what to look at is Collections (Java 2 Platform SE v1.4.2) . If you were to modify your code to use the shuffle function they you will be able to use a loop to set the color of the tiles in order, (and I agree with JonLane it would be easier if set color only set the color of the one tile). Then once all of the colors are set you can shuffle the whole collection of tiles and add them to the board in your shuffled order.

  8. #8
    Junior Member
    Join Date
    Feb 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random Colors Problem

    Sorry about this guys but I'm still having trouble. I just can't seem to get it to color only a certain amount of tiles. It either colors them all one color or gives me a nullpointer at

  9. #9
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Random Colors Problem

    Here I did some of it for you. You need to finish out the logic of how to set colors but you should get the idea. Really you do not even need the Tile class but I left it in because I am assuming you will be doing more with it later. Make sure you understand what I did and if you have any questions let me know.

    Your shuffle function never would have worked because you didn't add anything to the array on your Tile class. That is probably where you are throwing your null pointer. And it does not make sense that you have an array of tiles in that class, it should have been on your game board class. But really you did not need it because you already had all of your tiles stored in myTiles.

    Also, you were shuffling and adding your tiles to the gameboard before they were all created. You need to make all your tiles and then shuffle then add.



    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import java.util.Collections;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    public class GameBoard extends JPanel
    {
    	private static final int YELLOW = 39;
    	private static final int RED = YELLOW+46;
    	private static final int BLUE = RED+34;
    	private static final int GREEN = BLUE+52;
    	private static final int MAGENTA = GREEN+41;
    	private static final int CYAN = MAGENTA+44;
     
    	private ArrayList<Tile> tiles;
    	private int numRows = 16;
    	private int numCols = 16;
    	private int numTiles = numRows*numCols;
     
     
    	public GameBoard() {
    		tiles = new ArrayList<Tile>();
    		setSize(800,800);
    		buildTilePanel();
    	}
    	private void buildTilePanel() {
    		this.setBackground(Color.BLACK);
    		this.setPreferredSize(new Dimension(800, 800));
    		this.setLayout(new GridLayout(numRows, numCols));
     
    		for (int i = 0; i < numTiles; i++)
    		{
    			System.out.println("here: "+i);
    				tiles.add(new Tile());	
    				tiles.get(i).setColor(getColor(i));
    				//myTiles[i][j].addActionListener(eh);
    		}
    			Collections.shuffle(tiles);
     
    			for(Tile t: tiles)
    			{
    				this.add(t);
    			}
    	}
    	private Color getColor(int color)
    	{
    		Color rtn = Color.BLACK;
    		if(color<YELLOW)
    		{
    			rtn = Color.YELLOW;
    		}
    		else if(color<RED)
    		{
    			rtn = Color.RED;
    		}
    		else if( color<BLUE)
    		{
    			rtn = Color.BLUE;
    		}
    		//...Do the rest of the logic here
     
    		return(rtn);
    	}
     
    	public static void main( String args[] )
    	{
    		JPanel baseView = new GameBoard();
    		baseView.setPreferredSize(new Dimension(800,800));
    		baseView.setOpaque(false);
    		JFrame frame = new JFrame();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().add(baseView);
    		frame.setSize(800,800);
     
    		frame.setVisible(true);
    		frame.repaint();
    	}
    }

    import java.awt.Color;
    import java.awt.Dimension;
     
    import javax.swing.JButton;
     
    public class Tile extends JButton
    {
    	public Tile() {
    		super();
    		setPreferredSize(new Dimension(10, 10));
    	}
     
    	public void setColor(Color c)
    	{
    		this.setBackground(c);
    	}
    }

    **EDIT**
    also this may or may not be the best way to do this. That is for you to decide and modify where needed
    Last edited by mesatrin1; February 23rd, 2012 at 02:32 PM.

  10. #10
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: Random Colors Problem

    I literally wrote your method for you, with one small //TODO.

    Reread post 6, or check out mesatrin1's code.

    Once it is clear you have done that, I can offer further help, but it seems you are panicking because you are lost and it could be a good indication you need to slow down and with a pen and paper try to understand why our code is written that way. think out every step your program is taking and follow its progress on paper.

  11. #11
    Junior Member
    Join Date
    Feb 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random Colors Problem

    I got it guys! I kinda worked through it my own way. It may not be the most efficient but tell me what ya think. I ended up avoiding 2D arrays altogether and just used the gridlayout.

    Thanks for all the help!

    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 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;
     
    @SuppressWarnings("serial")
    public class GameBoard extends JFrame{
    	private int numRows = 16, numCols = 16;
    	Tile[] t = new Tile[256];
     
    	public static void main(String[] args) {
    		new GameBoard();
    	}
     
    	public GameBoard() {
    		setSize(800,800);
     
    		Container c = getContentPane();
    		c.setLayout(new BorderLayout());
     
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		setTitle("Random Colors");
     
    		JButton tilePanel = buildTiles();
    		c.add(tilePanel, BorderLayout.CENTER);
     
    		setResizable(false);
    		setVisible(true);
    	}
     
    	private JButton buildTiles() {
    		JButton board = new JButton();
    		board.setBackground(Color.BLACK);
    		board.setPreferredSize(new Dimension(800, 800));
    		board.setLayout(new GridLayout(numRows, numCols));
     
    		for(int i = 0; i < t.length; i++){
    			if(i < 39){
    				t[i] = new Tile(Color.YELLOW);
    				t[i].setColor();
    				board.add(t[i]);
    			}
    			else if(i >= 39 && i < 85){
    				t[i] = new Tile(Color.RED);
    				t[i].setColor();
    				board.add(t[i]);
    			}
    			else if(i >= 57 && i < 119){
    				t[i] = new Tile(Color.BLUE);
    				t[i].setColor();
    				board.add(t[i]);
    			}
    			else if(i >= 119 && i < 171){
    				t[i] = new Tile(Color.GREEN);
    				t[i].setColor();
    				board.add(t[i]);
    			}
    			else if(i >=171 && i < 212){
    				t[i] = new Tile(Color.MAGENTA);
    				t[i].setColor();
    				board.add(t[i]);
    			}
    			else if(i >= 212 && i < 256){
    				t[i] = new Tile(Color.CYAN);
    				t[i].setColor();
    				board.add(t[i]);
    			}
     
     
     
    		}
     
    		return board;
    	}
    }

    import java.awt.Color;
    import java.util.Random;
    import javax.swing.JButton;
     
    @SuppressWarnings("serial")
    public class Tile extends JButton{
    	Color color;
    	Tile[] colors = new Tile[256];
     
    	public Tile(Color c) {
    		color = c;
    	}
     
    	public Tile() {
     
    	}
     
    	public void setColor() {
    		for(int i = 0; i < colors.length; i++){
    			setBackground(color);
    			paintImmediately(0, 0, getWidth(), getHeight());	
    		}
    	}
     
    }

  12. #12
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: Random Colors Problem

    Looks much cleaner,
    perhaps 2d arrays was just to new of a concept for you,
    you should try to make a simple 2d array program now so next time you can use them as you like

Similar Threads

  1. Generation of random number using random class
    By JavaPF in forum Java SE API Tutorials
    Replies: 1
    Last Post: December 7th, 2011, 05:46 PM
  2. random problem
    By kantaki in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 15th, 2011, 08:00 AM
  3. How are the colors in Swing's UIManager used?
    By JerryH in forum AWT / Java Swing
    Replies: 0
    Last Post: January 27th, 2011, 10:50 PM
  4. Random Letter problem please help!
    By xs4rdx in forum Java Theory & Questions
    Replies: 1
    Last Post: March 28th, 2010, 12:27 PM
  5. Generation of random number using random class
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: April 16th, 2009, 07:10 AM

Tags for this Thread