12 Replies - 525 Views - Last Post: 27 April 2012 - 07:58 AM Rate Topic: -----

#1 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

java - moving a fillRect() on button press.

Posted 26 April 2012 - 01:57 PM

hey all,
Thanks for reading this and hope someone can guide me a bit here.

Im having trouble implementing this, and wondered if anyone could help.
My aim is to move the box left or right depending in the button press.
i then wish to chnage the colour of the box upon a button press (centre button).
Below is what i have come up with so far. (ive left in the other commented out attempts i have unsuccessfully tried)

Im stumped!
:helpsmilie:
package package2;

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/** 
Write an applet to produce a window that shows a box with 3 buttons above it.
When the middle button is clicked it should change the colour of the rectangle between red, green or blue.
When the left button is clicked the rectangle should move Left, when the right button is clicked it should move Right.
 **/
public class Q1_5_2 extends Applet implements ActionListener
{
// unique serial id to implement abstract class methods
	
private static final long serialVersionUID = 1L;
//declare buttons
Button btnLeft, btnChangeCol, btnRight;
//declare colours
Color red = Color.red;
Color blue = Color.blue;
Color green = Color.green;
boolean lBtn;
boolean rBtn;
boolean cBtn;
int move = 1;


/*Initialisations*/
	public void init()
	{	
		setSize(500, 500);
		//instantiate new button objects
		btnLeft = new Button("Left");
		//btnLeft.setEnabled(false);
		btnChangeCol = new Button("Change Colour");
		btnRight = new Button("Right");
		//add action listeners
		btnLeft.addActionListener(this);
		btnChangeCol.addActionListener(this);
		btnRight.addActionListener(this);
		//add to Applet
		add(btnLeft);
		add(btnChangeCol);
		add(btnRight);
		lBtn = false;
		rBtn = false;
		cBtn = false;	

		
	}//end init method
	
/*Action related code*/
	
	//override required due to the method not legally allowed implementation through an abstract class
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		//declare string var for use with button labels to establish button control via reference to them
		//String btnLabel = e.getActionCommand();
		System.out.println(lBtn);
		
		if (btnLeft.isFocusOwner())
		{

			lBtn = true;
			rBtn = false;
			cBtn = false;
			System.out.println("left button pressed");
			System.out.println("left button is.." + lBtn);
			System.out.println("right button is.." + rBtn);
			System.out.println("centre button is.." + cBtn);
		}
		else if (btnRight.isFocusOwner())
		{

			rBtn = true;
			lBtn = false;
			cBtn = false;
			System.out.println("right button pressed");
			System.out.println("left button is.." + lBtn);
			System.out.println("right button is.." + rBtn);
			System.out.println("centre button is.." + cBtn);
		}
		else if (btnChangeCol.isFocusOwner())
		{
			cBtn = true;
			rBtn =false;
			lBtn = false;
			System.out.println("change colour button pressed");
			System.out.println("left button is.." + lBtn);
			System.out.println("right button is.." + rBtn);
			System.out.println("centre button is.." + cBtn);
		}
	}//end action performed method

	/*Drawing related code*/
	public void paint(Graphics g)
	{
		int x = 75;
		int y= 50;
		int width = 350;
		int height = 200;
		
		g.setColor(green);
		g.fillRect(x, y, width, height);
			if (btnLeft.isFocusOwner())
			{
				x -=150;
				g.fillRect(x, y, width, height);
				repaint();
				lBtn = false;
				
			}
//			switch(choice)
//			{
//				case 'l': 					
//								x = x - 150;
//								//g.fillRect(x, y, width, height);
//								repaint();
//								lBtn = false;	
//				case 'r' : 
//							{
//								x +=150;
//								//g.fillRect(x, y, width, height);
//								repaint();
//								lBtn = false;
//							}
//			}

			
//			if (cBtn = true)
//			{
//				g.setColor(red);
//				g.fillRect(x, y, width, height);
//				repaint();
//			}
			
//		    for (int i = 0, count = blocks.length; i < count; i++) {
//		      g.fillRect(blocks[i].x, blocks[i].y, SIZE, SIZE);
//		    }
		
	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: java - moving a fillRect() on button press.

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2197
  • View blog
  • Posts: 5,224
  • Joined: 10-September 10

Re: java - moving a fillRect() on button press.

Posted 26 April 2012 - 02:37 PM

To change color, I would set an instance variable,

Color color = Color.GREEN;

And then in the actionPerformed() method for your change color button, something like:

if ( color.equals( Color.RED) )
{
	color = Color.GREEN;
}
else
{
	color = Color.RED;
}


and in your paint() method:

g.setColor(color);

Maybe that'll give you some ideas for moving the rectangle. If not, come back.

Edit: Oh! Why are you using Applet instead of the preferred JApplet? Have to?

This post has been edited by GregBrannon: 26 April 2012 - 02:38 PM

Was This Post Helpful? 1
  • +
  • -

#3 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2656
  • View blog
  • Posts: 11,204
  • Joined: 20-September 08

Re: java - moving a fillRect() on button press.

Posted 26 April 2012 - 02:47 PM

Your general pattern is incorrect. It should be as below. Never call repaint inside paint - it will cause recursion. Additions are prefaced with my username


/*
<applet code="Q1_5_2" width="400" height="300"></applet>
*/
import java.applet.Applet;

import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


/**

Write an applet to produce a window that shows a box with 3 buttons above it.

When the middle button is clicked it should change the colour of the rectangle between red, green or blue.

When the left button is clicked the rectangle should move Left, when the right button is clicked it should move Right.

**/
public class Q1_5_2 extends Applet implements ActionListener {
    // unique serial id to implement abstract class methods
    private static final long serialVersionUID = 1L;

    //declare buttons
    Button btnLeft;

    //declare buttons
    Button btnChangeCol;

    //declare buttons
    Button btnRight;

    //declare colours
    Color red = Color.red;
    Color blue = Color.blue;
    Color green = Color.green;
    boolean lBtn;
    boolean rBtn;
    boolean cBtn;
    int move = 1;

    //g00se
    int colorIndex;
    Color currentColor;
    Color[] COLORS = { Color.red, Color.blue, Color.green };

    /*Initialisations*/
    public void init() {
        setSize(500, 500);
        //g00se
        currentColor = COLORS[colorIndex];

        //instantiate new button objects
        btnLeft = new Button("Left");

        //btnLeft.setEnabled(false);
        btnChangeCol = new Button("Change Colour");

        btnRight = new Button("Right");

        //add action listeners
        btnLeft.addActionListener(this);

        btnChangeCol.addActionListener(this);

        btnRight.addActionListener(this);

        //add to Applet
        add(btnLeft);

        add(btnChangeCol);

        add(btnRight);

        lBtn = false;

        rBtn = false;

        cBtn = false;
    } //end init method

    /*Action related code*/

    //override required due to the method not legally allowed implementation through an abstract class
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnChangeCol) {
            colorIndex++;
            currentColor = COLORS[colorIndex % COLORS.length];
            repaint();
        }
    } //end action performed method

    /*Drawing related code*/
    public void paint(Graphics g) {
        int x = 75;

        int y = 50;

        int width = 350;

        int height = 200;

        g.setColor(currentColor);

        g.fillRect(x, y, width, height);
    }
}


This post has been edited by g00se: 26 April 2012 - 02:48 PM

Was This Post Helpful? 1
  • +
  • -

#4 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 12:00 AM

G00se and GregBrannon, you are both BEASTS of the CODE, thanks buds. Im just gonna have a cuppa tea then try and implement what you have offered here.
in answer to your question:
GregBrannon

Quote

Edit: Oh! Why are you using Applet instead of the preferred JApplet? Have to?


Well, we have been given a part assignment of programs to build and they predominately require applets, with part2 of assignment asking for a composition of built programs implemented though a web page.....

Consequently, I dont know enough about using swing really and thought if i could do it with whats there originally, then i could adapt to swing paradigms easily afterwards (but if you thikn i should go for swing then i will, cos i am aware that somethings are alot easier using that framework.
Mostly i have been just worried about using it for two reason:
firstly i dont know it realy yet
secondly, i started using netbeans originally and could not find a simple way to implement an applet development scenario, without implementing it through the new versions of , i think, javacard and this "netbeans platform" and was getting frustrated due to the amount of crap that happened when using it. Now it sounds a bit like im sounding off over netbeans(im not, but i do feel applets are hard (FOR BEGINNERS LIKE ME) to get up and running in netbeans if you wish to control how the applet is to be embedded for instance)
Please i must stress im one my own, have little by way of peer knowledge sharing amongst fellow students (infact it`ll be me that releases the final progs to the rest of class to try and understand, then change and pass off as their own etc.
All in all, i dont really know if what i have just said about netbeans is relevant either from a user perspective or just generally since the support for swing was terminated at release 7.1 (which i think was probably a partof my original reasoning too). Oh i dunno, i do know im really tired though :blink: and what ive just written looks like a babble of nonsensical gloop.
Ah well, bet you wished you never asked now !lol
Thanks for reading G00se,Greg, and others .
Will post back changes in a bit :)
gruffy :)

This post has been edited by gruffy: 27 April 2012 - 12:34 AM

Was This Post Helpful? 0
  • +
  • -

#5 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 12:32 AM

okay that has done an excellent job on the colors, but.
Could you perhaps tell me if it is possible to address the filRect(by coords or something) in order tha i might control its movement via the buttons either side of the change colour buttons.?
Many thanks for reading
Gruffy
Was This Post Helpful? 0
  • +
  • -

#6 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2197
  • View blog
  • Posts: 5,224
  • Joined: 10-September 10

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 12:56 AM

You've apparently made changes to your code, so please post the current source. The concepts are similar, though. You had an original starting point for your rectangle, the upper left corner. When the left button is pressed, move that starting point to the left and redraw - new starting point - and keep moving from each new starting point.
Was This Post Helpful? 1
  • +
  • -

#7 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 02:48 AM

View PostGregBrannon, on 27 April 2012 - 12:56 AM, said:

You've apparently made changes to your code, so please post the current source. The concepts are similar, though. You had an original starting point for your rectangle, the upper left corner. When the left button is pressed, move that starting point to the left and redraw - new starting point - and keep moving from each new starting point.


/*
<applet code="Q1_5_2" width="400" height="300"></applet>
*/
import java.applet.Applet;

import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


/**

Write an applet to produce a window that shows a box with 3 buttons above it.

When the middle button is clicked it should change the colour of the rectangle between red, green or blue.

When the left button is clicked the rectangle should move Left, when the right button is clicked it should move Right.

**/
public class Q1_5 extends Applet implements ActionListener {
    // unique serial id to implement abstract class methods
    private static final long serialVersionUID = 1L;

    //declare buttons
    Button btnLeft;

    //declare buttons
    Button btnChangeCol;

    //declare buttons
    Button btnRight;


    boolean lBtn;
    boolean rBtn;
    boolean cBtn;
    int move = 1;

    //create colour index for cycling colours
    int colorIndex;
    Color currentColor;
    Color[] COLORS = { Color.red, Color.blue, Color.green };

    /*Initialisations*/
    public void init() {
        setSize(500, 500);
        //instantiate colour index
        currentColor = COLORS[colorIndex];

        //instantiate new button objects
        btnLeft = new Button("Left");

        //btnLeft.setEnabled(false);
        btnChangeCol = new Button("Change Colour");

        btnRight = new Button("Right");

        //add action listeners
        btnLeft.addActionListener(this);

        btnChangeCol.addActionListener(this);

        btnRight.addActionListener(this);

        //add to Applet
        add(btnLeft);

        add(btnChangeCol);

        add(btnRight);

        lBtn = false;

        rBtn = false;

        cBtn = false;
    } //end init method

    /*Action related code*/


    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnChangeCol) {
            colorIndex++;
            currentColor = COLORS[colorIndex % COLORS.length];
            repaint();
        }
    } //end action performed method
//	public Graphics create(int x, int y, int width, int height) {
//	x = 75;
//	y = 100;
//	width = 350;
//	height = 200;
//	return ();
//}
    /*Drawing related code*/
    public void paint(Graphics g) {
        int x = 75;

        int y = 50;

        int width = 350;

        int height = 200;

        g.setColor(currentColor);

        g.fillRect(x, y, width, height);
//	      if ( isButtonPressed ) {
//        g.setColor( Color.black );
//    
//     g.fillRect( x-20, y, 40, 40 );
//     repaint();
//  }
//switch(choice)
//{
//	case 'l': 					
//					x = x - 150;
//					//g.fillRect(x, y, width, height);
//					repaint();
//					lBtn = false;	
//	case 'r' : 
//				{
//					x +=150;
//					//g.fillRect(x, y, width, height);
//					repaint();
//					lBtn = false;
//				}
//}


//if (cBtn = true)
//{
//	g.setColor(red);
//	g.fillRect(x, y, width, height);
//	repaint();
//}

//for (int i = 0, count = blocks.length; i < count; i++) {
// g.fillRect(blocks[i].x, blocks[i].y, SIZE, SIZE);
//}
    }
}





project folder for eclipse attached

So im guessing i need to create some sort of loop that addresses the coords, adds increment/decrement then moves fillRect left or right (obviously depending on which button pressed)
i want it to move on each button press.
Should i look to create a polling mechanism somwhow(sems overkill for just moving a fillrect on button press, which sounds more like event driven etc)
thanks Greg, your advice is gold x

Attached File(s)


This post has been edited by gruffy: 27 April 2012 - 02:49 AM

Was This Post Helpful? 0
  • +
  • -

#8 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2197
  • View blog
  • Posts: 5,224
  • Joined: 10-September 10

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 03:24 AM

Don't make it too hard. As with the color solution, define a starting point as instance variables:

int xTopLeft = 75;
int yTopLeft = 50;

Then, draw the first rectangle:

g.fillRect(xTopLeft, yTopLeft, width, height);

Then in your button listeners:

// if the left button is pressed:
xTopLeft -= 50; // or whatever your leftShift amount is

// if the right button is pressed:
xTopLeft += rightShift;

Hard code the values (e.g., leftShift, rightShift, up/down shifts) as little as possible. Use variables defined elsewhere so that changing the shift value is a single edit instead of several.

Remove the x/y value definitions from you paint() method. Maybe you can leave width and height there, maybe not, depending on how this exercise grows. With more advanced animation that involves changes to most (if not all) of the drawn object's characteristics, you won't define those characteristics in the drawing method. They will be initialized elsewhere and then controlled by other program methods.
Was This Post Helpful? 1
  • +
  • -

#9 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 03:24 AM

Okay , i have sorted it, thanks greg.
I should of taken better note of your statement
[quote]
The concepts are similar, though.
[quote/]
/*
<applet code="Q1_5_2" width="400" height="300"></applet>
*/
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;


/**

Write an applet to produce a window that shows a box with 3 buttons above it.

When the middle button is clicked it should change the colour of the rectangle between red, green or blue.

When the left button is clicked the rectangle should move Left, when the right button is clicked it should move Right.

**/
public class Q1_5 extends Applet implements ActionListener 
{
    int x = 75;

    int y = 50;

    int width = 350;

    int height = 200;
    // unique serial id to implement abstract class methods
    private static final long serialVersionUID = 1L;

    //declare buttons
    Button btnLeft;
    Button btnChangeCol;
    Button btnRight;

    int move = 1;

    //create colour index for cycling colours
    int colorIndex;
    Color currentColor;
    Color[] COLORS = { Color.red, Color.blue, Color.green };

    /*Initialisations*/
    public void init() {
        setSize(500, 500);
        //instantiate colour index
        currentColor = COLORS[colorIndex];
        //instantiate new button objects
        btnLeft = new Button("Left");
        //btnLeft.setEnabled(false);
        btnChangeCol = new Button("Change Colour");
        btnRight = new Button("Right");
        //add action listeners
        btnLeft.addActionListener(this);
        btnChangeCol.addActionListener(this);
        btnRight.addActionListener(this);
        //add to Applet
        add(btnLeft);
        add(btnChangeCol);
        add(btnRight);

    } //end init method

    /*Action related code*/
   
  
    /*Drawing related code*/
    public void paint(Graphics g) 
    {


        g.setColor(currentColor);

        g.fillRect(x, y, width, height);

    }

    public void actionPerformed(ActionEvent e) 
    {
//if middle button pressed change colour
        if (e.getSource() == btnChangeCol) 
        {
            colorIndex++;
            currentColor = COLORS[colorIndex % COLORS.length];
            repaint();
        }
//if leftbutton pressed move horizontal - 50 pixels
        if (e.getSource() == btnLeft)
        {
        	x -=50;
        	repaint();
        	
        }
//if right button pressed move horizontal + 50 pixels
        if (e.getSource() == btnRight)
        {
        	x +=50;
        	repaint();
        	
        }
    } //end action performed method

}



This completes the thread and maSSive Thankyous to Greg and G00se for being ACE
gruffy
Was This Post Helpful? 0
  • +
  • -

#10 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 03:55 AM

View PostGregBrannon, on 27 April 2012 - 03:24 AM, said:

Don't make it too hard. As with the color solution, define a starting point as instance variables:


I think i posted my revised solution when you must of been writing your response, please take the code i posted and run it, if you have time. i thikn i got it sorted, with almost all thanks going to you and your directed help.
How do i marked as solved again ?
x x x thanks GREG BRANNON x x x
The world should know you appear to be eXcellent human being !
now on to another task, probably have another thread on here in a minute for it . lol
Gruffy
Was This Post Helpful? 0
  • +
  • -

#11 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2197
  • View blog
  • Posts: 5,224
  • Joined: 10-September 10

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 04:39 AM

Appearances can be deceiving, but I appreciate the vote of confidence.

I can't run your code and won't be able to for some time. I gave the code a quick look and only noticed that the repaint() statement in your actionPerformed() method isn't required 3 times. One instance following the if statements would be sufficient.

I like what you did with the array of colors and how you controlled colorIndex to remain within the array boundaries. That's good stuff.
Was This Post Helpful? 1
  • +
  • -

#12 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2656
  • View blog
  • Posts: 11,204
  • Joined: 20-September 08

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 05:01 AM

The principles for responding to a 'move request' are the same - shift the coordinates and call repaint. The coordinates should be held as instance variables
Was This Post Helpful? 1
  • +
  • -

#13 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: java - moving a fillRect() on button press.

Posted 27 April 2012 - 07:58 AM

View PostGregBrannon, on 27 April 2012 - 04:39 AM, said:

Appearances can be deceiving, but I appreciate the vote of confidence.


Just bestowing what i see from the cover sleeve which you present here, which may hide the book but often reveals more insight unto the content inside etc, and well for what its worth , id say your a cool guy to know, and a helpful one too. But hey, maybe im a just little green behind the ears or just a :bananaman:
Anyway, thanks for all the code advice , I may have another thread going by tonight by the looks of things, I would sure appreciate it if you could spare it a thought for revision by your eyeballz.
Take it easy
Gruffy

and thanks again

View Postg00se, on 27 April 2012 - 05:01 AM, said:

The principles for responding to a 'move request' are the same - shift the coordinates and call repaint. The coordinates should be held as instance variables


G00se , you too have been a maSSive help in this and hope i might grab your attention later with another thread that looks like i`ll have to start if i cant solve it.
I wont say about it here cos i know we are not supposed to move subjects inthe same thread etc.
But thanks again boss man, youre a star alongside Mr Brannon.
Gruffy
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1