Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4014250
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T09:28:27+00:00 2026-05-20T09:28:27+00:00

I am trying to write a program in Java Swing that outputs a 10

  • 0

I am trying to write a program in Java Swing that outputs a 10 x 10 grid of geometric rectangles filled with randoms colors. However, when the user clicks on one of the rectangles within the display window the rectangle should repaint() and change to another color.

Thus far I have the rudimentary program running, but I can’t figure out how to implement a mouseListener to it in order to have the rectangles’ color change when a user clicks inside. At this point, the rectangles only repaint when the display window is expanded and minimized. Any advice/help would be greatly appreciated! Thanks!

Here is what I have so far…

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


public class ColorGrid extends JPanel {
   int w, x, y, z;
   Color c = new Color((int)(Math.random() * 0xFFFFFF));
   public void paint(Graphics g){
   Graphics2D g2 = (Graphics2D) g;

   setLayout(new GridLayout(10,10));

   int w = x = y = z = 0;
   for(int i=0;i<100;i++){
   Color c = new Color((int)(Math.random() * 0xFFFFFF));
   w+=10;
   x+=10;
   y+=50;
   z+=15; 

          g2.drawRect(w+10,x+30,y,z);
          g2.drawRect(w+10,x+30,y,z);               
          g2.fillRect(w+10,x+30,y,z);
          g2.setPaint(c);  
        } 
   }

   public static void main(String[] args) {
      JFrame f= new JFrame();
      f.setTitle("ColorGrid Display Window");
      f.setSize(200,200);
      f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
    });
    Container contentPane = f.getContentPane();
    contentPane.add(new ColorGrid());
    f.show();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T09:28:27+00:00Added an answer on May 20, 2026 at 9:28 am

    Any Component can have a MouseListener. JLabel is nice for a colored rectangle, as long as you make it opaque.

    Addendum: Having recommended MouseAdapter elsewhere, I should mention that one instance is enough.

    Addendum: This update adds the mouse listener in the ColorLabel constructor.

    ColorLabel picture

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    /** @see http://stackoverflow.com/questions/5136859 */
    public class ColorLabel extends JLabel {
    
        private static final int N = 10;
        private static final Random random = new Random();
        private static final MouseAdapter listener = new MouseAdapter() {
    
            @Override
            public void mousePressed(MouseEvent e) {
                ColorLabel label = (ColorLabel) e.getSource();
                label.setBackground(new Color(random.nextInt()));
            }
        };
    
        public ColorLabel() {
            this.setOpaque(true);
            this.setBackground(new Color(random.nextInt()));
            this.setPreferredSize(new Dimension(32, 32));
            this.addMouseListener(listener);
        }
    
        private void displayGrid() {
            JFrame f = new JFrame("ColorGrid");
            f.setLayout(new GridLayout(N, N));
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            for (int i = 0; i < N * N; i++) {
                final ColorLabel label = new ColorLabel();
                f.add(label);
            }
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new ColorLabel().displayGrid();
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to write a program in Java that uses osql to generate a
I am trying to write a Java program that reads an input file consisting
I'm trying to follow Java's JDBC tutorials to write a Java program that can
I'm trying to write a program in Java that when given an MxN matrix
I am trying to write a java program that will automatically download and name
I've been trying to write a program in java that can download a number
I'm trying to write a program that reads 2 numbers from the user and
I'm trying to write a Java program that can automatically log into Facebook. I've
I am trying to write a small java program that will accept a file
I'm trying to write a simple java program in Eclipse that prints these four

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.