[solved] How to change rectangle color using keyboard?

Hello JGO,

I have a question. Using only the Java 1.7/1.8 library, would you be able to change the color of a polygon draw by Java2D using keyboard input? For example, hitting the “R” key changes the polygon’s color to red. This is just something I have been wondering about, and want to know the answer to.

Thanks in advance,
DarkCart

you use a key listener to set the graphics color

How would you access the ‘Graphics g’ object in both the paint() and keyPressed() methods?

Since you said you want to change the color of the rectangle, please show the code you already have, since I would assume you already have a rectangle going.

Pixels (JFrame class) code:


package com.darkcart.game.pixels;
import java.awt.Dimension;

import javax.swing.*;

public class Pixels {

	Dimension d;
	Draw draw;

	public static void main(String[] args) {
		new Pixels();
	}

	public Pixels() {
		d = new Dimension(650, 500);
		JFrame frame = new JFrame();
		frame.setTitle("Pixels");
		frame.setSize(d);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		frame.setResizable(false);
		frame.setLocationRelativeTo(null);
		frame.add(new Draw());
	}
}

Draw (Graphics) Class:

package com.darkcart.game.pixels;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.JPanel;

public class Draw extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
	private static final long serialVersionUID = 1L;

	public int mouseX = 0, mouseY = 0;
	public static Color color;
	public Color purple;

	Random randomGenerator = new Random();
	int randomInt = randomGenerator.nextInt(5);

	public Draw() {
		addMouseMotionListener(this);
		addMouseListener(this);
		addKeyListener(this);
	}
	


	public void mouseDragged(MouseEvent e) {
	}

	public void mouseMoved(MouseEvent e) {
		repaint();
		mouseX = e.getX();
		mouseY = e.getY();
		repaint();
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void paint(Graphics g) {

		purple = new Color(178, 102, 255);

		if (randomInt == 0) {
			color = Color.red;
		}
		if (randomInt == 1) {
			color = Color.orange;
		}
		if (randomInt == 2) {
			color = Color.yellow;
		}
		if (randomInt == 3) {
			color = Color.green;
		}
		if (randomInt == 4) {
			color = Color.blue;
		}
		if (randomInt == 5) {
			color = purple;
		}
		super.paint(g);
		g.setColor(color);
		g.fillRect(mouseX, mouseY, 32, 32);
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
		if (key == KeyEvent.VK_R) {
			color = Color.red;
		}

	}

	@Override
	public void keyReleased(KeyEvent e) {
		return;

	}

	@Override
	public void keyTyped(KeyEvent e) {
		return;

	}

Does that help?

Add a member to your ‘Draw’ class called rectangleColor and when you go to draw on the Graphics object g in paint(Graphics g), use g.setColor(rectangleColor) before drawing the rectangle. The in one of your input listeners just change rectangleColor based on the keypress.

package com.darkcart.game.pixels;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.JPanel;

public class Draw extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
	private static final long serialVersionUID = 1L;

	public int mouseX = 0, mouseY = 0;
	public static Color color;
	public Color purple;

	Random randomGenerator = new Random();
	int randomInt = randomGenerator.nextInt(5);

	public Draw() {
		addMouseMotionListener(this);
		addMouseListener(this);
		addKeyListener(this);

+		purple = new Color(178, 102, 255);
	}
	


	public void mouseDragged(MouseEvent e) {
	}

	public void mouseMoved(MouseEvent e) {
-		repaint();
		mouseX = e.getX();
		mouseY = e.getY();
		repaint();
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void paint(Graphics g) {

-		purple = new Color(178, 102, 255);

-		if (randomInt == 0) {
-			color = Color.red;
-		}
-		if (randomInt == 1) {
-			color = Color.orange;
-		}
-		if (randomInt == 2) {
-			color = Color.yellow;
-		}
-		if (randomInt == 3) {
-			color = Color.green;
-		}
-		if (randomInt == 4) {
-			color = Color.blue;
-		}
-		if (randomInt == 5) {
-			color = purple;
-		}
		super.paint(g);
		g.setColor(color);
		g.fillRect(mouseX, mouseY, 32, 32);
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
-		if (key == KeyEvent.VK_R) {
-			color = Color.red;
-		}

+		switch(key)
+		{
+		case KeyEvent.VK_R:
+			color = Color.red;
+			break;
+		case KeyEvent.VK_O:
+			color = Color.orange;
+			break;
+		case KeyEvent.VK_Y:
+			color = Color.yellow;
+			break;
+		case KeyEvent.VK_G:
+			color = Color.green;
+			break;
+		case KeyEvent.VK_B:
+			color = Color.blue;
+			break;
+		case KeyEvent.VK_P:
+			color = purple;
+			break;
+		}

	}

	@Override
	public void keyReleased(KeyEvent e) {
		return;

	}

	@Override
	public void keyTyped(KeyEvent e) {
		return;

	}

I ended up finding something that worked, only to find that for some reason, it only works sometimes, and not others. Why is this?

What does that even mean…? How can we know what you’re talking about if you only provide such a vague description of your issue?

What I mean is, my solution I found works once, then never works again. I have no idea what’s going on, so I can’t describe it in much detail.

… You never posted anything about your solution so we have no idea what the issue could be.

Sorry, here is what I thought was a permanent fix.


if (keyCode == KeyEvent.VK_R) {
			rectangleColor = Color.red;
}
if (keyCode == KeyEvent.VK_O) {
                        rectangleColor = Color.orange;
}
if (keyCode == KeyEvent.VK_Y) {
                        rectangleColor = Color.yellow;
}
if (keyCode == KeyEvent.VK_G) {
                        rectangleColor = Color.green;
}
if (keyCode == KeyEvent.VK_B) {
                       rectangleColor = Color.blue;
}
if (keyCode == KeyEvent.VK_P) {
                       rectangleColor = purple // This is my own version of purple, as the Java API doesn't have one.

And do you put that code into any sort of a loop? Or is that code only run once?

The code only runs once.

Well yeah there’s your issue… Of course if you only run through the code once the the color will only change once.

So, I need to put it in a loop. Is that what you’re saying?

Let me answer: Yes.

Where would this loop go?

You should really go back and really figure out your games graphical architecture.

Most Java novices tend to start with Graphics2D (which you are already using). However, you’ve fallen into a “trap” of sorts that I see a lot of people fall into. You do not have a gameloop. You have your game logic only work once a key is pressed. While this works on a very small scale, it will cause you problems down the road.

I would set up my application this way:

  • Main Class which creates my own screen for drawing

  • Screen class (extends JPanel) like you have
    [list][li]Needs to have a subclass (or can be combined with the screen) which implements Runnable[list][li]This is to control your games “FPS”[/li]
    [/list][/li]

  • Game Class[li]This is to control your games logic. If you want, you can tie it in directly with the screen (in the same thread), or you can attempt multithreading.[/li]
    [/list]

Using this style of architecture, you can change the color of the rectangle (via keypress) in the game class, and then on the next redraw, the screen class will show it’s new color. This way, you do not have to redraw the game every time a key is pressed, and therefore have your application run with more consistency.

Take a step back and study game loops, there is a good article on here somewhere.