Results 1 to 13 of 13
  1. #1
    arnonneder is offline Member
    Join Date
    Jan 2014
    Posts
    9
    Rep Power
    0

    Default Changing a rectangle color with MouseListener

    Hi,

    I'm new to Swing and I'm trying to build a program which sets a fill color for a rectangle. Each time the mouse is clicked the fill color changes according to the position of the mouse's X and Y.
    I succeeded to create a JFrame with a changing background according to the Mouse's position, but I can't seem to change the color of the rectangle (defined in MyPanel class).

    This is the current code, thanks in advance for any suggestions!

    Java Code:
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    
    public class MouseEventDemo2 extends JFrame {
    
      // Private variables
       private JTextField tfMouseX; // to display mouse-click-x
       private JTextField tfMouseY; // to display mouse-click-y
       private JTextField tfMouseXpos; // to display the mouse X position
       private JTextField tfMouseYpos; // to display the mouse Y position
    
       // to write the mouse X and Y position
       // in a text area
       // when the mouse is being clicked
       private JTextArea taMouseXY;
    
       private JTextArea taMouseXYpos;
    
      // Constructor - Setup the UI
       public MouseEventDemo2() {
    	  Container cp = getContentPane();
          cp.setLayout(new FlowLayout()); // "this" frame sets layout
    
         // Label
          add(new JLabel("X-Click: ")); // "this" frame adds component
    
         // TextField
          tfMouseX = new JTextField(4); // 10 columns
          tfMouseX.setEditable(false); // read-only
          add(tfMouseX); // "this" frame adds component
    
         // Label
          add(new JLabel("Y-Click: ")); // "this" frame adds component
    
         // TextField
          tfMouseY = new JTextField(4);
          tfMouseY.setEditable(false); // read-only
          add(tfMouseY); // "this" frame adds component
    
          // Text Area
    	  taMouseXY = new JTextArea(1, 20);
    	  add(taMouseXY); // "this" frame adds component
    
          // Label
    	  add(new JLabel("X-Pos: ")); // "this" frame adds component
    
    	  // TextField
    	  tfMouseXpos = new JTextField(4); // 10 columns
    	  tfMouseXpos.setEditable(false); // read-only
          add(tfMouseXpos); // "this" frame adds component
    
          // Label
    	  add(new JLabel("Y-Pos: ")); // "this" frame adds component
    
    	  // TextField
    	  tfMouseYpos = new JTextField(4);
    	  tfMouseYpos.setEditable(false); // read-only
          add(tfMouseYpos); // "this" frame adds component
    
          // Text Area
    	  taMouseXYpos = new JTextArea(1, 20);
    	  add(taMouseXYpos); // "this" frame adds component
    
    
    
          this.addMouseListener(new MouseListener() {
          	@Override
    	    	public void mouseClicked(MouseEvent e) {
    	        	tfMouseX.setText(e.getX() + "");
    	        	tfMouseY.setText(e.getY() + "");
    
    	        	taMouseXY.setText("");
    	        	taMouseXY.append("R: ");
    	        	taMouseXY.append(e.getX() + "");
    	        	taMouseXY.append(" G: ");
    	        	taMouseXY.append(" B: ");
    	        	taMouseXY.append(e.getY() + "");
    	        	taMouseXY.append(".");
    
    
    	        }
    
    	    @Override
    	    	public void mousePressed(MouseEvent e) { }
    
    		@Override
    			public void mouseReleased(MouseEvent e) { }
    
    		@Override
    			public void mouseEntered(MouseEvent e) { }
    
    		@Override
    			public void mouseExited(MouseEvent e) { }
    		});
    
    	  // Adding MouseMotionListener in order to get the mouse position
    	  // using the mouseMoved method
    	  this.addMouseMotionListener(new MouseMotionListener() {
    		@Override
    			public void mouseMoved(MouseEvent e) {
    				tfMouseXpos.setText(e.getX() + "");
    			    tfMouseYpos.setText(e.getY() + "");
    
    			    taMouseXYpos.setText("");
    			    taMouseXYpos.append("R: ");
    				taMouseXYpos.append(e.getX() + "");
    				taMouseXYpos.append(" G: ");
    				taMouseXYpos.append(" B: ");
    				taMouseXYpos.append(e.getY() + "");
    	        	taMouseXYpos.append(".");
    
    				Color bg = new Color(e.getX(), 0, e.getY());
    	        	getContentPane().setBackground(bg);
    			}
    
    
    		@Override
       			public void mouseDragged(MouseEvent e) { }
    		});
    
    
    
    	  // Exiting the window when clicking on the close window button
    	  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setTitle("MouseEvent Demo"); // "this" Frame sets title
          setSize(255, 255);     // "this" Frame sets initial size
          MyPanel mp = new MyPanel();
          cp.add(mp);
          setVisible(true);      // "this" Frame shows
    
       }
    
    class MyPanel extends JPanel {
    	int x = 200;
       	int y = 100;
       	Color co = new Color(x, 0, y);
    
       	public MyPanel() {
       		this.addMouseListener(new MouseListener() {
       			@Override
       				public void mouseClicked(MouseEvent e) {
       					x = e.getX();
       					y = e.getY();
       					co = new Color(x,0,y);
       					repaint();
       				}
    
       			@Override
       				public void mousePressed(MouseEvent e) { }
    
       			@Override
       				public void mouseReleased(MouseEvent e) { }
    
       			@Override
       				public void mouseEntered(MouseEvent e) { }
    
       			@Override
       				public void mouseExited(MouseEvent e) { }
       		});
           }
    
           public void paintComponent(Graphics g) {
               super.paintComponent(g);
               g.setColor(co);
               g.fillRect(0,0,20,20);
           }
    }
    
    
    
    
    
       public static void main(String[] args) {
    	   SwingUtilities.invokeLater(new Runnable() {
    		   @Override
             	public void run() {
    				new MouseEventDemo2(); // Let the constructor do the job
    			}
    		});
    	}
    }
    Last edited by arnonneder; 03-03-2014 at 05:33 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Changing a rectangle color with MouseListener

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.\

    Try debugging the code by adding some println() statements to see where the code is executing and to see the values of variables as their values are changed.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,380
    Rep Power
    5

    Default Re: Changing a rectangle color with MouseListener

    First, you have a couple or problems in general design. Instead of extending JFrame (which almost always is a bad idea), extend JPanel, and add that panel to your JFrame. In your case this offers an added advantage of ensuring that you have access to a real 255 x 255 panel. The 255 x 255 JFrame includes the borders so you don't have access to all the color ranges. (so your size also needs to be 256 x 256 to get 0 to 255 ).

    Use setPreferredSize on your JPanel followed by a JFrame.pack() command to size everything properly.

    Now for you question. The answer is it is working just fine. The problem is that your color is changing based on the coordinate system of the smaller 20 x 20 square. This will almost always be very dark because you can't get an x or y higher than 19.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  4. #4
    arnonneder is offline Member
    Join Date
    Jan 2014
    Posts
    9
    Rep Power
    0

    Default Re: Changing a rectangle color with MouseListener

    Thanks for all the comments!

    Jim- now I see that the program works. I didn't see it before, because the color of the square changes only when the mouse is clicked inside the square borders. What I actually want to achieve is that it will change when the mouse is clicked inside the whole JFame borders, according to the X and Y positions.

    any suggestions?

    Thanks in advance.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Changing a rectangle color with MouseListener

    when the mouse is clicked inside the whole JFame borders
    One way would be to define a Rectangle that has the boundaries you want and use its contains() method with the location of the mouse click.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,380
    Rep Power
    5

    Default Re: Changing a rectangle color with MouseListener

    Okay, so I assume you want the following:

    1. Moving the mouse around will alter the color selection based on x,y.
    2. When you click x,y, the small square will "latch" the color and keep it there until you click the mouse again.
    3. During mouse movements, effectively ignore the center square.

    If I am correct you can simply draw a small square in the JPanel, the current latched color. So as you paint the field as it changes, keep painting the
    small square with the latched color. So you don't really need a second panel or the associated listeners. Assuming of course that
    I understand what you want. It also means you need to extend JPanel and override paintComponent.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    arnonneder is offline Member
    Join Date
    Jan 2014
    Posts
    9
    Rep Power
    0

    Default Re: Changing a rectangle color with MouseListener

    Quote Originally Posted by jim829 View Post
    Okay, so I assume you want the following:

    1. Moving the mouse around will alter the color selection based on x,y.
    2. When you click x,y, the small square will "latch" the color and keep it there until you click the mouse again.
    3. During mouse movements, effectively ignore the center square.

    If I am correct you can simply draw a small square in the JPanel, the current latched color. So as you paint the field as it changes, keep painting the
    small square with the latched color. So you don't really need a second panel or the associated listeners. Assuming of course that
    I understand what you want. It also means you need to extend JPanel and override paintComponent.

    Regards,
    Jim
    You're right- that's exactly what I want to achieve. But I still don't totally understand how to implement your suggestions- didn't I create a little square and overrode painComponent? And what do you mean by - you don't really need a second panel or the associated listeners?

    Thanks!

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,380
    Rep Power
    5

    Default Re: Changing a rectangle color with MouseListener

    You need one Panel (excluding the JFrame - remember, don't subclass JFrame, but do subclass JPanel). That becomes your panel.
    In your motion listener you are constantly changing the colors and setting the background, followed by a repaint. You should also save
    that color to another variable (say bg).

    Then in your mouseClicked method, simply assign the bg color to another variable called currentColor. Then do a repaint().

    In your paint component method. Simply draw the small square, using the color currentColor. This last color will not change until
    you click the mouse again. And notice that the small square will become invisible when you do the click. That is because at that
    moment, bg and currentColor are the same.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  9. #9
    arnonneder is offline Member
    Join Date
    Jan 2014
    Posts
    9
    Rep Power
    0

    Default Re: Changing a rectangle color with MouseListener

    Thanks!

    I changed the code so now it only subclasses JPanel. I succeeded to make the background color to change according to the mouse position, but now I face a new problem - the small rectangle doesn't appear in the frame.

    my current code is:

    Java Code:
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    
    public class MouseEventDemo3 extends JPanel implements  MouseListener, MouseMotionListener{
    
    	JTextField tfMouseX, tfMouseY;
    	JPanel totalGUI;
    	Color bg;
    	public JPanel createContentPane (){
    
    	totalGUI = new JPanel();
    
    	totalGUI.setLayout(null);
    
            JLabel mouseX = new JLabel("X-Click: ");
    	mouseX.setLocation(0,0);
    	mouseX.setSize(70, 30);
    	mouseX.setHorizontalAlignment(0);
    	mouseX.setForeground(Color.black);
            totalGUI.add(mouseX);
    
            JLabel mouseY = new JLabel("Y-Click: ");
    	mouseY.setLocation(100,0);
    	mouseY.setSize(70, 30);
    	mouseY.setHorizontalAlignment(0);
    	mouseY.setForeground(Color.black);
            totalGUI.add(mouseY);
    
            tfMouseX = new JTextField(4);
    	tfMouseX.setLocation(60,5);
    	tfMouseX.setSize(40,20);
    	tfMouseX.addMouseListener(this);
            totalGUI.add(tfMouseX);
            tfMouseX.setEditable(false);
    
            tfMouseY = new JTextField(4);
    	tfMouseY.setLocation(160,5);
    	tfMouseY.setSize(40,20);
    	tfMouseY.addMouseListener(this);
    	totalGUI.add(tfMouseY);
            tfMouseY.setEditable(false);
    
    	totalGUI.addMouseListener(this);
    	totalGUI.addMouseMotionListener(this);
    	totalGUI.setOpaque(true);
        	return totalGUI;
    	}
    
    	@Override
    	public void mouseClicked(MouseEvent e) {
    		tfMouseX.setText(e.getX() + "");
    		tfMouseY.setText(e.getY() + "");
    	}
    
    	@Override
    	public void mousePressed(MouseEvent e) { }
    
    	@Override
    	public void mouseReleased(MouseEvent e) { }
    
    	@Override
    	public void mouseEntered(MouseEvent e) { }
    
    	@Override
    	public void mouseExited(MouseEvent e) { }
    
    	@Override
    	public void mouseMoved(MouseEvent e) {
    
    		bg = new Color(e.getX(), 0, e.getY());
    		totalGUI.setBackground(bg);
    	}
    
    	@Override
    	public void mouseDragged(MouseEvent e) { }
    
    	public void paintComponent(Graphics g) {
    
    		super.paintComponent(g);
    		Color co = new Color(0, 0, 0);
                    g.setColor(co);
    		g.fillRect(150,150, 50,50);
        }
    
    	private static void createAndShowGUI() {
    
    		//JFrame.setDefaultLookAndFeelDecorated(true);
    		JFrame frame = new JFrame("MouseEvent Demo");
    
    		MouseEventDemo3 demo = new MouseEventDemo3();
                    frame.setContentPane(demo.createContentPane());
    
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(255, 255);
        	        frame.setVisible(true);
    	}
    
    	public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    Last edited by arnonneder; 03-03-2014 at 11:36 PM.

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,380
    Rep Power
    5

    Default Re: Changing a rectangle color with MouseListener

    Ugh! You made additional changes. That makes it extremely hard to help you because it may negate my earlier suggestions. You were 90% there. And do not use absolute positioning. Your earlier layout manager was the way to go. So I suggest you revert to your original code and extend JPanel. Don't create a second JPanel, it isn't necessary. Just create a JFrame and add the panel to it. Onceyou get it working you can then fine tune the GUI.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Changing a rectangle color with MouseListener

    Try doing some debugging by adding println() statements to see what methods are called.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    arnonneder is offline Member
    Join Date
    Jan 2014
    Posts
    9
    Rep Power
    0

    Default Re: Changing a rectangle color with MouseListener

    Thanks for all the comments!

    It seems to be working :)

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Changing a rectangle color with MouseListener

    What did you change to get it to work?
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Changing Image color
    By Frecow in forum Java 2D
    Replies: 0
    Last Post: 04-04-2011, 10:16 AM
  2. Mouse Click changes Color of Rectangle
    By DocIcarus in forum New To Java
    Replies: 1
    Last Post: 11-23-2010, 01:53 PM
  3. How to change color of area contained by rectangle
    By thayalan in forum AWT / Swing
    Replies: 2
    Last Post: 06-04-2009, 04:48 AM
  4. Replies: 1
    Last Post: 03-31-2009, 03:15 AM
  5. Changing the color of text
    By Lang in forum New To Java
    Replies: 1
    Last Post: 11-04-2007, 09:51 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •