Difference between revisions of "CISC181 F2017 JFrameExample"

From class_wiki
Jump to: navigation, search
(Created page with "===Main class=== <nowiki> package cisc181.mylab_2; // Christopher Rasmussen import javax.swing.JFrame; public class Lab2 { public static void main(String[] args...")
(No difference)

Revision as of 02:21, 19 September 2017

Main class

 package cisc181.mylab_2;

 // Christopher Rasmussen

 import javax.swing.JFrame;

 public class Lab2 {

     public static void main(String[] args) {

       JFrame myFrame = new JFrame();

       myFrame.setSize(500, 500);
       myFrame.setTitle("Color Test");
       myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       ColorJComponent myComponent = new ColorJComponent(500, 500);
       myFrame.add(myComponent);

       myFrame.setVisible(true);   // setVisible() *after* add() is the norm
     }
 }
 

Custom JComponent class

 package cisc181.mylab_2;

 // Christopher Rasmussen

 import javax.swing.JComponent;
 import java.awt.Color;
 import java.awt.Graphics;

 public class MyJComponent extends JComponent {

     public void paintComponent(Graphics g) {

         final int SIDE_LENGTH = 16;
         int gridInterval = 20;
         int xOffset = (gridInterval - SIDE_LENGTH) / 2;   // so that grid is centered
         int yOffset = xOffset;

         // grid of alternating colors and shapes

         for (int y = 0; y < getHeight(); y += gridInterval) {
             for (int x = 0; x < getWidth(); x += gridInterval) {

                 // red squares on even rows and columns

                 if ((y % (2 * gridInterval)) == 0 || (x % (2 * gridInterval)) == 0) {
                     g.setColor(Color.RED);
                     g.fillRect(xOffset + x, yOffset + y, SIDE_LENGTH, SIDE_LENGTH);
                 } 

                 // blue circles otherwise 

                 else {
                     g.setColor(Color.BLUE);
                     g.fillOval(xOffset + x, yOffset + y, SIDE_LENGTH, SIDE_LENGTH);
                 }
             }
         }
     }
 }