Colour Box GUI

Arman Majumder 0 Tallied Votes 195 Views Share

A program that creates a grid panel of desired dimensions and changes the colour randomly of each grid box upon dragging the mouse over the selected region.

// Arman Majumder
// Colour Box GUI

   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;
   import java.io.*;
   import java.util.Random;
   
    public class ColourBox extends JPanel
   {
       public ColourBox(Color backColor)
      {
         setBackground(backColor);
         addMouseListener(new PanelListener());
      }
      
       public void paintComponent(Graphics g)
      {
         super.paintComponent(g);     	  
      }
   	
       private class PanelListener extends MouseAdapter
      {
          public void mouseEntered(MouseEvent e)    //Color change is determined by dragging the mouse
          //public void mouseEntered(MouseEvent e)  //Color change is determined by clicking the mouse 
         {	
            Random color = new Random();
            int red = color.nextInt(256);
            int green = color.nextInt(256);
            int blue = color.nextInt(256);
            Color backDrop = new Color(red, green, blue);
            setBackground(backDrop);
            repaint();
         }
      }
      
       public static void main(String [] args)
      {
         JFrame random = new JFrame();
         random.setSize(400,400);
         random.setTitle("Colour Box");
         random.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
         String rows = JOptionPane.showInputDialog("Enter the Rows:");
         int row = Integer.parseInt(rows);
         String columns = JOptionPane.showInputDialog("Enter the Columns:");
         int col = Integer.parseInt(columns);
         JOptionPane.showConfirmDialog(null, "Are these the correct demensions: "
            +row+" x "+col+ "?", 
            "Yes or No", JOptionPane.YES_NO_OPTION);   	
         
         Container pane = random.getContentPane();
         pane.setLayout(new GridLayout(row,col));
         
         for (int i = 1; i <=(row * col); i++)
         {
            JPanel panel = new ColourBox(Color.white);    
            panel.setBackground(Color.white);
            pane.add(panel);
         }
         random.setVisible(true);
      } 
   }
cms271828 2 Junior Poster

Interesting, but not very fun.
But nicely constructed, and a good tool for beginners to look at to get a flavour of guis.

smart90 0 Newbie Poster

nice.. it very interesting

amos wang 0 Newbie Poster

i like it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.