advictoriam

Untitled

Nov 20th, 2018
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. import javax.swing.JComponent;
  2. import java.awt.Graphics;
  3. import java.awt.Graphics2D;
  4. import java.awt.Rectangle;
  5. import java.awt.Color;
  6.  
  7. /**
  8.    Draws colored squares.
  9.  */
  10. public class ColorSquaresComponent extends JComponent
  11. {
  12.    private String colors;
  13.    private int wide;
  14.    private int high;
  15.    private int size;
  16.    
  17.    /**
  18.       Constructs a component for a drawing made up of colored squares.
  19.       @param col the color codes of all squares in the drawing.
  20.       @param w the width of the drawing
  21.       @param h the height of the drawing
  22.       @param sideLength the side length of each square
  23.    */
  24.    public ColorSquaresComponent(String col, int w, int h, int boxSize)
  25.    {
  26.       colors = col;
  27.       wide = w;
  28.       high = h;
  29.       size = boxSize;
  30.    }    
  31.    
  32.    private Color getSquareColor(char code)
  33.    {
  34.       if (code == 'R') return Color.RED;
  35.       if (code == 'G') return Color.GREEN;
  36.       if (code == 'B') return Color.BLUE;
  37.       if (code == 'C') return Color.CYAN;
  38.       if (code == 'M') return Color.MAGENTA;
  39.       if (code == 'Y') return Color.YELLOW;
  40.       if (code == 'K') return Color.BLACK;
  41.       return Color.WHITE;      
  42.    }
  43.        
  44.    public void paintComponent(Graphics g)
  45.    {
  46.       Graphics2D g2 = (Graphics2D) g;
  47.       for(int i = 0; i < 20; i++)
  48.       {
  49.          for(int j = 0; j < 20; j++)
  50.          {
  51.             g2.setColor(getSquareColor(colors.charAt(j+(i*20))));
  52.             g2.fillRect(j * size, i * size, size, size);
  53.          }
  54.       }
  55.     }
  56. }
Add Comment
Please, Sign In to add comment