Difference between revisions of "CISC181 S2017 JFrameExample"

From class_wiki
Jump to: navigation, search
(Custom JComponent class)
(Main class)
 
Line 8: Line 8:
 
  import javax.swing.JFrame;
 
  import javax.swing.JFrame;
  
  public class Lab3 {
+
  public class Lab2 {
  
 
     public static void main(String[] args) {
 
     public static void main(String[] args) {

Latest revision as of 10:45, 20 February 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("Drawing window");
         myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         MyJComponent myComponent = new MyJComponent();
         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);
                 }
             }
         }
     }
 }