a java programme to colour in a grid?

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 4779 Views - Last Post: 29 March 2012 - 05:34 PM Rate Topic: ***** 1 Votes

#1 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

a java programme to colour in a grid?

Posted 19 March 2012 - 11:14 AM

Hi I need a java programme to:

1)create a 6x6 grid.
2)ask the user to choose from 6 colours to fill a square (i have written an enum and had them declared already- see below)
3)test to see if one row or column has 5 colours in and autocomplete with the final colour. also it should not allow the user to click on any squares in that row or column if it is complete.
4) if a square has already been filled in and gets clicked again it should go back to blank/empty colour.
5) if a square is going to be coloured the same as one already in that row/column the square should be left blank and an error message displayed saying why and allowing the user to try again
the starting pattern is to be read in from a file i.e.
R1 C2 Green
where R1 is 1st row and C2 is second column.

the file reading seems ok but i have no idea where to go from there. i have a little bit of code which is below

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class ColourInfo extends JButton {
        
       private static int emptySquares=0;
      
       public static final Color red;
       public static final Color yellow;
       public static final Color green;
       public static final Color blue;
       public final Color purple = new Color( 128, 0, 128);
       public final Color brown = new Color(139,69,19);
       
       static enum Colours {RED, BLUE, GREEN, YELLOW, PURPLE, BROWN}
        
        private Colours colour = null;
        
        private void setColour(Colours c){
        colour = c;
        
        }     
        
        
}



here is the main class where the game will be created etc


import assignmentv2.ColourInfo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;


public class ColourGame extends JFrame{
    public final int SIZE = 6;
    
   //An array of buttons which can be searched for wins
    private ColourInfo [][] cinfo;  
    
    //The constructor 
    public ColourGame() { 
        // Initializes the various components
        // Could be a separate method called initComponents()
        
        //Set up the frame details
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("COM162 Assignment 1 Student ID 100157842");
        setLocationRelativeTo(null);
   	setLayout(new GridLayout(SIZE,SIZE));

        //Creates space to store the arry of buttons
        cinfo = new ColourInfo [SIZE][SIZE];
	
	for (int row = 0;  row < SIZE; row++)
            for (int column = 0;  column < SIZE; column++) {
                cinfo[row][column] = new ColourInfo(this, row, column);
                add(cinfo[row][column]);
            }
        
       //  Finish the frame
       pack();
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: a java programme to colour in a grid?

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10803
  • View blog
  • Posts: 40,259
  • Joined: 27-December 08

Re: a java programme to colour in a grid?

Posted 19 March 2012 - 12:02 PM

JButton already has setBackground() and setForeground() methods, which you can use. Don't reinvent the wheel here with the Colors as well. If you want to limit to six colors, just use a Color[]. You could also handle this with Icons, as JButton has methods like getPressedIcon() and setPressedIcon(). Check out the documentation.
Was This Post Helpful? 3
  • +
  • -

#3 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 23 March 2012 - 06:52 AM

thanks for that. i have now adopted a new way of going about it. I am using Jedit (much easier than netbeans) and have created a grid and was thinking of doing the following:
when any button is pressed open a new window and ask for the colour (using mouse listener).
use if statements to test what colour has been picked (again using mouse listener)

i was just wondering how i would go about testing if a button has been pressed twice?

below is the code i have so far for creating the grid

thanks


import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.JOptionPane;

public class ButtonGrid extends JFrame {
	
	public static void main(String[] args) {
		int rows = 6;
		int cols = 6;
		int size = 600;
		
		ButtonGrid grid = new ButtonGrid(rows, cols);
		
		grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		grid.setPreferredSize(new Dimension(size, size));
		grid.pack();
		grid.setLocationRelativeTo(null);
		grid.setVisible(true);
	}
	
	public ButtonGrid(int rows, int cols) {
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for (int i = 0; i < 36; i++) {
			JButton button = new JButton("");
			pane.add(button);
		}
	}
	
}


Was This Post Helpful? 0
  • +
  • -

#4 Mylo  Icon User is offline

  • Knows all, except most.

Reputation: 265
  • View blog
  • Posts: 747
  • Joined: 11-October 11

Re: a java programme to colour in a grid?

Posted 23 March 2012 - 07:14 AM

You can just create a variable.

int timesPressed

onclick()
{
  timesPressed++
  if (timesPressed == 2)
    // do something
}


Was This Post Helpful? 1
  • +
  • -

#5 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 23 March 2012 - 08:15 AM

Also would my colour array look like this? and do i need to declare the variables as i am?


public static final Color red = Color.RED;
	public static final Color yellow = Color.Yellow;
	public static final Color green = Color.GREEN;
	public static final Color blue = Color.BLUE;
	public final Color purple = new Color( 102, 0, 102);
	public final Color brown = new Color(102,51,0);
	
	Color[] palette = {Color.YELLOW, Color.RED, Color.PINK, new Color(102,0,102), Color.GREEN,Color.BLUE, new Color(102,51,0), Color.WHITE};
	


or should it look like the one below?


public static final Color red = Color.RED;
	public static final Color yellow = Color.Yellow;
	public static final Color green = Color.GREEN;
	public static final Color blue = Color.BLUE;
	public final Color purple = new Color( 102, 0, 102);
	public final Color brown = new Color(102,51,0);
	
	Color[] palette = {yellow, red, purple, green, blue, brown};




thanks again
Was This Post Helpful? 0
  • +
  • -

#6 Mylo  Icon User is offline

  • Knows all, except most.

Reputation: 265
  • View blog
  • Posts: 747
  • Joined: 11-October 11

Re: a java programme to colour in a grid?

Posted 23 March 2012 - 08:28 AM

The first one's variable delcarations if you place them in the array. Also, why are some declared static and others not?

Personally though, I would have

Color[] palette = {Color.YELLOW, Color.RED, Color.PINK, new Color(102,0,102), Color.GREEN,Color.BLUE, new Color(102,51,0), Color.WHITE};



but both would work.

You could also have something like

ArrayList<Color> colours = new ArrayList<Color>();

public MyClass()
{
  addColours();
}

public addColours()
{
  colours.add(Color.RED);
  colours.add(Color.BLUE);
}



Was This Post Helpful? 1
  • +
  • -

#7 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 24 March 2012 - 04:24 AM

Hi again. I have now made 2 classes to attempt to solve this problem. I have my main class Buttongrid which creates my 6x6 grid. I then have a seperate class which brings up 6 buttons in a frame with the colour choices. I was wondering how would i get the second class to open and colour the button in with the choice made when a button was pressed on the 6x6 grid then close once a buton is pressed? Also hoiw would i store my buttons in a 2d array when i create them?

here is the code:

ButtonGrid

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonGrid extends JFrame implements ActionListener {
	
	private int numClicks = 0;
	
	public static void main(String[] args) {
		int rows = 6;
		int cols = 6;
		int size = 600;
		
		ButtonGrid grid = new ButtonGrid(rows, cols);
		grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		grid.setPreferredSize(new Dimension(size, size));
		grid.pack();
		grid.setLocationRelativeTo(null);
		grid.setVisible(true);
	}//end main
	
	public ButtonGrid(int rows, int cols) {
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for(int j =0; j<rows; j++)
		for (int i = 0; i < cols; i++) {
			JButton button = new JButton("");
			button.addActionListener(this);
			button.setBackground(new Color(100,100,100));
			pane.add(button);
		}
	}//end buttonGrid
	
	public void actionPerformed(ActionEvent e) {
                numClicks++;
        }
        
}//end class



and here is choices.

import java.awt.*;
import javax.swing.*;

public class ColourChoice extends JFrame {
	
	public static void main(String[] args) {
		int rows = 6;
		int cols = 6;
		int size = 300;
		
		ColourChoice choice = new ColourChoice(rows, cols);
		choice.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		choice.setPreferredSize(new Dimension(size/2, size));
		choice.pack();
		choice.setLocationRelativeTo(null);
		choice.setVisible(true);
	}
	
	public ColourChoice(int rows, int cols) {
		String[] colourName ={"RED","GREEN","BLUE","YELLOW","PURPLE","BROWN"};
		Color[] choices = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, new Color(102, 0, 102), new Color(102, 51, 0)};
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for (int i = 0; i < choices.length; i++) {
			JButton button = new JButton(""+colourName[i]);
			button.setForeground(new Color(100,100,100));
			button.setBackground(choices[i]);
			pane.add(button);
		}
	}
	
}



thanks.
Was This Post Helpful? 0
  • +
  • -

#8 Mylo  Icon User is offline

  • Knows all, except most.

Reputation: 265
  • View blog
  • Posts: 747
  • Joined: 11-October 11

Re: a java programme to colour in a grid?

Posted 24 March 2012 - 04:58 AM

You probably want to have a main class, which contains two instances of your two classes.

You can have your main class implement ActionListener, then add actionlisteners to the two other classes buttons. This should invoke your mains actionPerformed method, then you can handle what you need to their.

class main implements ActionListener
{
 buttonarray btnarr;
 menu amenu;

 // btnarr.button1.addActionListener(this);
 // menu.button1.addActionListener(this);

 public void actionPerformed(...)
 {
    // do what you want here
 }

}

class buttonarray
{

}

class menu
{

}



I'm not very good with complicated class hierachies, but I think MVC (Model-View-Controller) is useful in these situtations. There is a tutorial by GregBrannon in the tutorials section aswell as a StateManager tutorial by Macosxnerd101 which is similar.
Was This Post Helpful? 1
  • +
  • -

#9 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 24 March 2012 - 05:59 AM

thanks for that. I have managed to merge the 2 classes together and was wondering how would i go about setting a buttons background colour when a button is pressed in the smaller window that appears? also afetr a colour is chosen how would i make the suare go blank if clicked again?

here is the new version

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonGrid extends JFrame implements ActionListener {
	
	private int numClicks = 0;
	
	public static void main(String[] args) {
		int rowsGrid = 6;
		int colsGrid = 6;
		int sizeGrid = 600;
		
		ButtonGrid grid = new ButtonGrid(rowsGrid, colsGrid);
		grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		grid.setPreferredSize(new Dimension(sizeGrid, sizeGrid));
		grid.pack();
		grid.setLocationRelativeTo(null);
		grid.setVisible(true);
	}//end main
	
	public ButtonGrid(int rows, int cols) {
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for(int j =0; j<rows; j++)
		for (int i = 0; i < cols; i++) {
			JButton button = new JButton("");
			button.addActionListener(this);
			button.setBackground(new Color(100,100,100));
			pane.add(button);
		}
	}//end buttonGrid
	
	public void actionPerformed(ActionEvent e) {
                numClicks++;
                int rows = 6;
		int cols = 6;
		int size = 300;
                ColourChoice choice = new ColourChoice(rows, cols);
		choice.setPreferredSize(new Dimension(size/2, size));
		choice.pack();
		choice.setVisible(true);
        }
        
        
public class ColourChoice extends JFrame{
	
	public ColourChoice(int rows, int cols) {
		String[] colourName ={"RED","GREEN","BLUE","YELLOW","PURPLE","BROWN"};
		Color[] choices = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, new Color(102, 0, 102), new Color(102, 51, 0)};
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for (int i = 0; i < choices.length; i++) {
			JButton button = new JButton(""+colourName[i]);
			button.setForeground(new Color(100,100,100));
			button.setBackground(choices[i]);
			pane.add(button);
		}
	}
	
}//end choice class

}//end class



View PostMylo, on 23 March 2012 - 07:14 AM, said:

You can just create a variable.

int timesPressed

onclick()
{
  timesPressed++
  if (timesPressed == 2)
    // do something
}



would this go in the main method or the class?

regards
Was This Post Helpful? 0
  • +
  • -

#10 Mylo  Icon User is offline

  • Knows all, except most.

Reputation: 265
  • View blog
  • Posts: 747
  • Joined: 11-October 11

Re: a java programme to colour in a grid?

Posted 24 March 2012 - 07:23 AM

This is where you have to start thinking about problems and how you solve them. Break things down into logical steps. This could be a basic solution (pseduo code):

class main implements ActionListener
{
 buttonarray btnarr;
 menu amenu;
 Color currentColor = ...

 public void actionPerformed(...)
 {
    if click on grid square
       if grid square colour not default
          grid square color = currentColor
       else
          grid square color = default
    else if click on menu color
      currentColor = clicked menu color
    
 }

}


Was This Post Helpful? 1
  • +
  • -

#11 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 24 March 2012 - 09:27 AM

OK thanks. I am still slightly confused as to how to make the button clicked to change colour. I can get the pane of the colourChoice window to change but not the button that was clicked to actually open the window. i have tried subbing in button and it says it cnat find the symbol. here is the code i am currently running

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonGridv2 extends JFrame implements ActionListener {
	
	private int numClicks = 0;
	private int choiceOpen = 0;
	
	public static void main(String[] args) {
		int rowsGrid = 6;
		int colsGrid = 6;
		int sizeGrid = 600;
		
		ButtonGridv2 grid = new ButtonGridv2(rowsGrid, colsGrid);
		grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		grid.setPreferredSize(new Dimension(sizeGrid, sizeGrid));
		grid.pack();
		grid.setLocationRelativeTo(null);
		grid.setVisible(true);
	}//end main  
	
	public ButtonGridv2(int rows, int cols) {
		int rowsGrid = 6;
		int colsGrid = 6;
		int sizeGrid = 600;
		JButton[][] buttons;
		buttons = new JButton[sizeGrid][sizeGrid];
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for(int j =0; j<rows; j++)
		for (int i = 0; i < cols; i++) {
			JButton button = new JButton("");
			buttons[rowsGrid][colsGrid] = buttons[j][i];
			button.addActionListener(this);
			button.setBackground(new Color(100,100,100));
			pane.add(button);
		}
	}//end buttonGrid
	
	public void actionPerformed(ActionEvent e) {
		if(choiceOpen <1){
			numClicks++;
			int rows = 6;
			int cols = 1;
			int size = 300;
			ColourChoicev2 choice = new ColourChoicev2(rows, cols);
			choice.setPreferredSize(new Dimension(size/2, size));
			choiceOpen = 1;
			choice.pack();
			choice.setVisible(true);
			choice.addWindowListener(new WindowAdapter()
				{
					
					public void windowClosing(WindowEvent e)
					{
						choiceOpen = 0;
					}
				});
		}
		
        }//end actionperformed       
        
        public class ColourChoicev2 extends JFrame {
        	
		public JButton redButton;
		public JButton yellowButton;
		public JButton blueButton;
		public JButton greenButton;
		public JButton purpleButton;
		public JButton brownButton;
		public JPanel panel;
		
		public ColourChoicev2(int rows, int cols)
		{
			redButton = new JButton("Red");
			yellowButton = new JButton("Yellow");
			blueButton = new JButton("Blue");
			greenButton = new JButton("Green");
			purpleButton = new JButton("Purple");
			brownButton = new JButton("Brown");
			
			boolean redButtonOn = false;
			
			redButton.addActionListener(new RedButtonListener());
			yellowButton.addActionListener(new YellowButtonListener());
			blueButton.addActionListener(new BlueButtonListener());
			greenButton.addActionListener(new GreenButtonListener());
			purpleButton.addActionListener(new PurpleButtonListener());
			brownButton.addActionListener(new BrownButtonListener());
			
			panel = new JPanel();
			
			panel.add(redButton);
			panel.add(yellowButton);
			panel.add(blueButton);
			panel.add(greenButton);
			panel.add(purpleButton);
			panel.add(brownButton);
			add(panel);
			setVisible(true);
		}
		
		private class RedButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				panel.setBackground(Color.RED);				
			}
		}
		
		private class YellowButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				panel.setBackground(Color.YELLOW);				
			}
		}
		
		private class BlueButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				panel.setBackground(Color.BLUE);				
			}
		}
		
		private class GreenButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				panel.setBackground(Color.GREEN);				
			}
		}
		
		private class PurpleButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				panel.setBackground(new Color(102,0,102));
			}
		}
		
		private class BrownButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				panel.setBackground(new Color(102,51,0));
			}
		}
	}
        //not used but needed to implement windowlistener
        public void windowActivated(WindowEvent e){};
        public void windowClosed(WindowEvent e){};
        public void windowClosing(WindowEvent e){};
        public void windowDeiconified(WindowEvent e){};
        public void windowDeactivated(WindowEvent e){};
        public void windowIconified(WindowEvent e){};
        public void windowOpened(WindowEvent e){};
        
}//end class



Was This Post Helpful? 0
  • +
  • -

#12 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 25 March 2012 - 04:17 PM

how would i now get the button to return to default colour only if it has been set any other colour and then is clicked again? thanks. New code below:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonGridv2 extends JFrame implements ActionListener {
      
    public static void main(String[] args) {
    	int rowsGrid = 6;
    	int colsGrid = 6;
    	int sizeGrid = 600;
    	
    	ButtonGridv2 grid = new ButtonGridv2(rowsGrid, colsGrid);
    	grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	grid.setPreferredSize(new Dimension(sizeGrid, sizeGrid));
    	grid.pack();
    	grid.setLocationRelativeTo(null);
    	grid.setVisible(true);
    	
    }//end main  
    
    public ButtonGridv2(int rows, int cols) {
    	int rowsGrid = 6;
    	int colsGrid = 6;
    	int size = 600;
    	JButton[][] buttons;
    	buttons = new JButton[rowsGrid][colsGrid];
    	Container pane = getContentPane();
    	pane.setLayout(new GridLayout(rows, cols));
    	for(int j =0; j<rows; j++)
    	for (int i = 0; i < cols; i++) {
    	    buttons[j][i] = new JButton("");
    	    buttons[j][i].setOpaque(true);
    	    buttons[j][i].addActionListener(this);
    	    buttons[j][i].setBackground(Color.GRAY);
    	    pane.add(buttons[j][i]);
    	}
    }//end buttonGrid
    
    public void actionPerformed(ActionEvent e) {   	
        int rows = 6;
        int cols = 1;
        int size = 300;
        ColourChoicev2 choice = new ColourChoicev2(rows, cols, (JButton) e.getSource());
        choice.setPreferredSize(new Dimension(size/2, size));
        choice.pack();
        choice.setVisible(true);  
    }//end actionperformed       
    
    class ColourChoicev2 extends JFrame {
    	
    	public JButton redButton;
    	public JButton yellowButton;
    	public JButton blueButton;
    	public JButton greenButton;
    	public JButton purpleButton;
    	public JButton brownButton;
    	public JPanel panel;
    	private JButton clickedButton;
    	
    	public ColourChoicev2(int rows, int cols, JButton button)
    	{
    	    redButton = new JButton("Red");
    	    yellowButton = new JButton("Yellow");
    	    blueButton = new JButton("Blue");
    	    greenButton = new JButton("Green");
    	    purpleButton = new JButton("Purple");
    	    brownButton = new JButton("Brown");
    	    
    	    clickedButton = button;
    	    
    	    redButton.addActionListener(new RedButtonListener());
    	    yellowButton.addActionListener(new YellowButtonListener());
    	    blueButton.addActionListener(new BlueButtonListener());
    	    greenButton.addActionListener(new GreenButtonListener());
    	    purpleButton.addActionListener(new PurpleButtonListener());
    	    brownButton.addActionListener(new BrownButtonListener());
    	    
    	    panel = new JPanel();
    	    
    	    panel.add(redButton);
    	    panel.add(yellowButton);
    	    panel.add(blueButton);
    	    panel.add(greenButton);
    	    panel.add(purpleButton);
    	    panel.add(brownButton);
    	    add(panel);
    	    setVisible(true);
    	}
    	
    	public class RedButtonListener implements ActionListener
    	{
    	    public void actionPerformed(ActionEvent e)
    	    {        	
    	    	clickedButton.setBackground(Color.RED); 
    	    	dispose();
    	    }
    	}
    	
    	private class YellowButtonListener implements ActionListener
    	{
    	    public void actionPerformed(ActionEvent e)
    	    {
    	    	clickedButton.setBackground(Color.YELLOW); 
    	    	dispose(); 
    	    }
    	}
    	
    	private class BlueButtonListener implements ActionListener
    	{
    	    public void actionPerformed(ActionEvent e)
    	    {   
    	    	clickedButton.setBackground(Color.BLUE);    
    	    	dispose();          
    	    }
    	}
    	
    	private class GreenButtonListener implements ActionListener
    	{
    	    public void actionPerformed(ActionEvent e)
    	    {    	    	
    	    	clickedButton.setBackground(Color.GREEN);   
    	    	dispose();
    	    }
    	}
    	
    	private class PurpleButtonListener implements ActionListener
    	{
    	    public void actionPerformed(ActionEvent e)
    	    {    	    	
    	    	clickedButton.setBackground(new Color(102,0,102));
    	    	dispose();
    	    }
    	}
    	
    	private class BrownButtonListener implements ActionListener
    	{
    	    public void actionPerformed(ActionEvent e)
    	    {    	    	
    	    	clickedButton.setBackground(new Color(102,51,0));
    	    	dispose();
    	    }
    	}
    }//end colour choice
 }//end class


Was This Post Helpful? 0
  • +
  • -

#13 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 26 March 2012 - 03:01 AM

managed to solve the button issues with help. now i was just wondering how would i go about checking if there is 1 square of each colour in any row and column and if there is how would i then disable that row or column from opening a new choice window? thanks :)

here is the code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonGridv3 extends JFrame implements ActionListener 
{
	private ColourChoicev2 choice = null;
	
	public static void main(String[] args) 
	{
		int rowsGrid = 6;
		int colsGrid = 6;
		int sizeGrid = 600;
		ButtonGridv3 grid = new ButtonGridv3(rowsGrid, colsGrid);
		grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		grid.setPreferredSize(new Dimension(sizeGrid, sizeGrid));
		grid.pack();
		grid.setLocationRelativeTo(null);
		grid.setVisible(true);
		
	}//end main  
	
	public ButtonGridv3(int rows, int cols) 
	{
		int rowsGrid = 6;
		int colsGrid = 6;
		int sizeGrid = 600;
		JButton[][] buttons;
		buttons = new JButton[sizeGrid][sizeGrid];
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(rows, cols));
		for(int j =0; j<rows; j++)
			for (int i = 0; i < cols; i++) 
			{
				buttons[j][i] = new JButton("");
				buttons[j][i].setOpaque(true); 
				buttons[j][i].setName("");      
				buttons[j][i].addActionListener(this);      
				buttons[j][i].setBackground(Color.darkGray);
				pane.add(buttons[j][i]);
			}
	}//end buttonGrid
	
	public void actionPerformed(ActionEvent e) 
	{
		JButton button = (JButton) e.getSource();
		
		//if ((button.getName()).equals(""))  // Uncomment this if you don't want colour window, if already coloured button is clicked.
		//{
		
		// this is to check if any previous window is showing or not
		// if one found , dispose that and open a new one
		// for the new button.
		if ( choice != null && choice.isShowing())
			choice.dispose();
		numClicks++;
		int rows = 6;
		int cols = 1;
		int size = 300;
		choice = new ColourChoicev2(rows, cols, (JButton) e.getSource());
		choice.setPreferredSize(new Dimension(size/3, size));
		choice.pack();
		choice.setVisible(true);
		if ((button.getName()).equals("ColouredButton"))    
		{
			button.setBackground(Color.darkGray);
			button.setName("");
		}
		//}
		/*else if ((button.getName()).equals("ColouredButton")) 
		{
		button.setBackground(Color.darkGray);
		}*/
		//}
	}//end actionperformed       
	
	class ColourChoicev2 extends JFrame 
	{
		public JButton redButton;
		public JButton yellowButton;
		public JButton blueButton;
		public JButton greenButton;
		public JButton purpleButton;
		public JButton brownButton;
		public JPanel panel;
		private JButton clickedButton; 
		
		public ColourChoicev2(int rows, int cols, JButton button)
		{
			redButton = new JButton("Red");
			yellowButton = new JButton("Yellow");
			blueButton = new JButton("Blue");
			greenButton = new JButton("Green");
			purpleButton = new JButton("Purple");
			brownButton = new JButton("Brown");
			
			clickedButton = button;
			
			redButton.addActionListener(new RedButtonListener());
			yellowButton.addActionListener(new YellowButtonListener());
			blueButton.addActionListener(new BlueButtonListener());
			greenButton.addActionListener(new GreenButtonListener());
			purpleButton.addActionListener(new PurpleButtonListener());
			brownButton.addActionListener(new BrownButtonListener());
			
			panel = new JPanel();
			
			panel.add(redButton);
			panel.add(yellowButton);
			panel.add(blueButton);
			panel.add(greenButton);
			panel.add(purpleButton);
			panel.add(brownButton);
			add(panel);
			//setVisible(true);
		}
		
		private class RedButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				clickedButton.setBackground(Color.RED);
				clickedButton.setName("ColouredButton");
				dispose();
			}
		}
		
		private class YellowButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{             
				clickedButton.setBackground(Color.YELLOW); // added by me in every method.
				clickedButton.setName("ColouredButton");
				dispose(); // added by me in every method
			}
		}
		
		private class BlueButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{ 
				clickedButton.setBackground(Color.BLUE);    
				clickedButton.setName("ColouredButton");
				dispose();          
			}
		}
		
		private class GreenButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				clickedButton.setBackground(Color.GREEN);   
				clickedButton.setName("ColouredButton");
				dispose();
			}
		}
		
		private class PurpleButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{

				clickedButton.setBackground(new Color(102,0,102));
				clickedButton.setName("ColouredButton");
				dispose();
			}
		}
		
		private class BrownButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				clickedButton.setBackground(new Color(102,51,0));
				clickedButton.setName("ColouredButton");
				dispose();
			}
		}
	}
}//end class



Was This Post Helpful? 0
  • +
  • -

#14 Mylo  Icon User is offline

  • Knows all, except most.

Reputation: 265
  • View blog
  • Posts: 747
  • Joined: 11-October 11

Re: a java programme to colour in a grid?

Posted 26 March 2012 - 03:29 AM

Nice to see progress :smile2:

One thing thoughL You don't need a seperate class to handle each button. It can just be one class with if/if-else statement determining which button was pressed. It might also be easier to use the set/getActionCommand() method.

As for determining if a row contains all colours, I like to do stuff like that by having each item removing it's colour from a list, then checking if the list is empty.

                // I'm assuming colours have all 6 colours in them
		ArrayList<Color> colours = new ArrayList<Color>();
				
		public boolean isUniqueRow(int row)
		{
			ArrayList<Color> check = checkColours;
			// for each button in specified row
			////  check.remove(button.color);   
			// if check.size() > 0
			//// return false;
			// return true;
		}



Also, I suggest you don't create a new JFrame for your buttons every click. But instead use setVisible(true/false). I personally think leaving it open would be better, or moving it to the side of the grid in another panel.

This post has been edited by Mylo: 26 March 2012 - 03:32 AM

Was This Post Helpful? 0
  • +
  • -

#15 why_always_me  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 19-March 12

Re: a java programme to colour in a grid?

Posted 26 March 2012 - 03:43 AM

View PostMylo, on 26 March 2012 - 03:29 AM, said:

Nice to see progress :smile2:

One thing thoughL You don't need a seperate class to handle each button. It can just be one class with if/if-else statement determining which button was pressed. It might also be easier to use the set/getActionCommand() method.

As for determining if a row contains all colours, I like to do stuff like that by having each item removing it's colour from a list, then checking if the list is empty.

                // I'm assuming colours have all 6 colours in them
		ArrayList<Color> colours = new ArrayList<Color>();
				
		public boolean isUniqueRow(int row)
		{
			ArrayList<Color> check = checkColours;
			// for each button in specified row
			////  check.remove(button.color);   
			// if check.size() > 0
			//// return false;
			// return true;
		}



Also, I suggest you don't create a new JFrame for your buttons every click. But instead use setVisible(true/false). I personally think leaving it open would be better, or moving it to the side of the grid in another panel.


Hi thanks for that :) i was just wondering do i just create the arraylist my self so it would look like:

ArrayList<Color> colours = new ArrayList<Color>(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, new Color(102, 0, 102), new Color(102, 51, 0));



Also would the single button listener class look like this:

private class ButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				if(clickedButton.equals(redButton)){
                                clickedButton.setBackground(Color.RED);
				clickedButton.setName("ColouredButton");
                               }else if(clickedButton.equals(blueButton)){
                               clickedButton.setBackground(Color.BLUE);
				clickedButton.setName("ColouredButton");
                                }//etc
				dispose();
			}
		}


thanks
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2