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.


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

Results 1 to 2 of 2

Thread: Changing colours of objects

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Thanked 0 Times in 0 Posts

    Default Changing colours of objects

    Hey all,

    1st let me say, this IS a school assignment, so I don't expect you to answer directly. However I would like a nudge or two in the right direction so I can actually complete the assignment.

    Okay. We have to write a program which uses anonymous inner classes of Mouse Events to change the colour of a shape in a JPanel.

    So...... this is what I have......

    Circle class:
    import java.awt.*;
    // Class definition
    public class Circle extends Point {
        protected int size;
        // Constructor method declaration
        public Circle() {
            // set size and offset y co-ordinate to display below point
            size = 50;
            yPos = 100;
        // Method to update new size of the circle
        public void reSize(int newSize) {
            size = size + newSize;
        // An overiding method to display circle on screen as inherited method from class Point not suitable
        public void display(Graphics g) {
            // Call method fillOval from class Graphics to draw the circle of variable diameter of size 
            g.fillOval(xPos, yPos, size, size); 

    This just creates a circle from class called point. Simple enough.

    Point class:
    import java.awt.*;
    // Class definition
    public class Point {
        protected int xPos, yPos;
        // Constructor method declaration
        public Point() {
            xPos = 100;
            yPos = 100;
        // Method to update new position of point on screen
        public void moveXY(int newX, int newY) {
            xPos = xPos + newX;
            yPos = yPos + newY;
        // Cannot resize a point but method required to support polymorphism
        public void reSize(int newSize) {
        // Method to print X,Y co-ordinates of point on screen
        public void outputXYCoords(Graphics g) {
            g.drawString("X Coord = " + xPos + "   Y Coord = " + yPos, 5, yPos-10);
        // Method to draw point on screen at new X.Y position
        public void display(Graphics g) {
            g.fillOval(xPos, yPos, 5, 5);

    Again, not very complicated.

    Main code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics.*;
    import java.awt.Color.*;
    import javax.swing.*;
    import javax.swing.event.*;
    // Class definition
    public class PolyMorphDemo extends JPanel implements ActionListener {
        private JLabel mouseStatus;
        private int startX, startY, endX, endY, diffX, diffY;
        private JButton makeBigger, makeSmaller;
        private JComboBox shapeChoice;
        private Point firstPoint;
        private Circle firstCircle;
        private Square firstSquare;
        private Doughnut firstDoughnut;
        private Point aShape;
        // Constructor method declaration
        public PolyMorphDemo() {
            makeBigger = new JButton("Make Bigger");
            makeSmaller = new JButton("Make Smaller");
            shapeChoice = new JComboBox();
            // Instantiate shape classes
            firstPoint = new Point();
            firstCircle = new Circle();
            firstSquare = new Square();
            firstDoughnut = new Doughnut();
            // Initially assign aShape a Point object
            aShape = firstPoint;
            // Create a new window using the Swing class JFrame and add this panel
        public void actionPerformed(ActionEvent e) {
            // Manipulate respective object when buttons pressed
            mouseStatus = new JLabel();
            this.addMouseListener(new MouseAdapter() {
                // This is the bit I'm having trouble with - this simply doesn't implement
                Color color = Color.darkGray;
                public void paint(Graphics g) {
                // The next bit works fine apart from the this.color line - it just doesn't recolour the shape to gray
                public void mousePressed(MouseEvent me){
                    mouseStatus.setText("Mouse pressed X: " +
                                       me.getX() + " Y: " + me.getY());
                    startX = me.getX();
                    startY = me.getY();
                    this.color = Color.darkGray;
            this.addMouseListener(new MouseAdapter() {
                // Same problem as above
                Color color = Color.black;
                public void paint(Graphics g) {
                // Same as above - this moves the object fine
                public void mouseReleased(MouseEvent me) {
                    mouseStatus.setText("Mouse released X: " +
                                       me.getX() + " Y: " + me.getY());
                    endX = me.getX();
                    endY = me.getY();
                    diffX = endX - startX;
                    diffY = endY - startY;
                    mouseStatus.setText("Mouse has moved X: " +
                                       diffX + " Y: " + diffY);
                    this.color = Color.black;
            if (e.getSource() == makeBigger) {
            else if (e.getSource() == makeSmaller) {
            // checkbox assigns object to aShape
            else if (e.getSource() == shapeChoice) {
                if (shapeChoice.getSelectedItem().equals("Circle"))
                    aShape = firstCircle;
                else if (shapeChoice.getSelectedItem().equals("Square"))
                    aShape = firstSquare;
                else if (shapeChoice.getSelectedItem().equals("Point"))
                    aShape = firstPoint;
                else if (shapeChoice.getSelectedItem().equals("Doughnut"))
                    aShape = firstDoughnut;
            // Ask Java to repaint the window to reflect the updates made
        // Provide this method to instruct Java what to do when repainting the window
        public void paintComponent(Graphics g) {
            // Call the respective methods from respective class to print the new co-ordinate values
            // Call the respective methods from respective class to redraw the shape
        // Create a window frame
        public void makeFrame() {
            // Instantiate a window frame using Swing class JFrame
            JFrame frame = new JFrame("PolyMorphDemo");
            // When the window is closed terminate the application
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
            // set initial size of window
            frame.setSize(800, 600);
            // add the current object to the centre of the frame and make visible
            frame.getContentPane().add(this, BorderLayout.CENTER);

    As you can tell, there are also 2 other classes (square and doughnut) which create a square and a doughnut (who'd have thought it, eh? ) in place of a circle or point.

    So basically, every piece of functionality (moving according to the mouse drag), making bigger, smaller etc. works.

    The only problem is that I simply cannot get the object to change colour to gray when the mouse button is pressed, and turn back to black when it's released. I've tried several avenues to get this working, and none have worked, so if someone could provide a little aid, that'd be very much appreciated.



  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    North Wales
    My Mood
    Thanked 115 Times in 106 Posts
    Blog Entries

    Default Re: Changing colours of objects

    Hey there tommyf, I know you didn't come here for a lecture, but It would be worthwhile for you to read up on Java best practices, as there are a few iffy code segments in the program - i.e. Avoid naming your classes the same as pre-existing libraries as It can cause some confusion (Point).

    Instead of naming each and every issue as to why you can't achieve your goals, I made a basic program demonstrating painting with Java, while listening for mouse events.

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public final class Drawing extends JPanel implements MouseMotionListener, MouseListener{
    	private int x,y; //x and y coords 
    	private Color color; //colour of the circle
    	private final int CIRCLE_SIZE = 25; //size
    	public Drawing(){
    		x = 0;
    		y = 0;
    		color = Color.PINK;
    		addMouseListener(this); //add listeners
    	public void paintComponent(Graphics g){
    		Graphics2D g2 = (Graphics2D) g; //down cast
    		g2.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE); //draw circle
    	public void mousePressed(MouseEvent e) {
    		color = Color.YELLOW;
    	public void mouseReleased(MouseEvent e) {
    		color = Color.BLUE;
    	public void mouseDragged(MouseEvent e) {
    		x = e.getX();
    		y = e.getY();
    	public void mouseClicked(MouseEvent e) {}
    	public void mouseEntered(MouseEvent e) {}
    	public void mouseExited(MouseEvent e) {}
    	public void mouseMoved(MouseEvent e) {}
    	public static void main(String... args){
    		final JFrame frame = new JFrame("JPF Example");
    		frame.add(new Drawing());

    If you compile that program yourself, and read the code you should notice how mouse listeners work and a cleaner way to paint.
    Obviously that is just an example and isn't immediately going to solve all your questions, which it isn't meant to, but hopefully you will learn through it.
    Last edited by newbie; January 22nd, 2012 at 05:06 PM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

Similar Threads

  1. Replies: 1
    Last Post: January 3rd, 2012, 06:28 PM
  2. Changing my GUI help
    By Xrrak in forum AWT / Java Swing
    Replies: 13
    Last Post: August 10th, 2011, 03:11 PM
  3. changing GUI
    By timmin in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 3rd, 2011, 08:16 AM
  4. Replies: 4
    Last Post: March 2nd, 2011, 11:30 AM
  5. Parameter's value is never changing
    By chronoz13 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 27th, 2009, 05:29 AM