Java GUI

JFrames

Screen Shot 2014-10-27 at 1.45.46 PM

Some basic JFrame applications:

Screen Shot 2014-10-28 at 5.47.35 AM

An empty frame

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
/**
 * Write a description of class RectangleObject here.
 
 */
public class RectangleObject extends JComponent
{
    public void paintComponent(Graphics g)
    {
      Graphics2D g2 = (Graphics2D) g;

      // Construct a rectangle object
      Rectangle box = new Rectangle(5, 10, 20, 30);
      // draw the rectangle
      g2.draw(box);  
    }
   
}

The JFrame class:

import javax.swing.JFrame;
/**
 * Draw an empty frame using JFrame.
 * 
 */

public class RectangleJFrame
{
       public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(300,400);
        frame.setTitle("A Rectanlge Object in a JFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        RectangleObject aRectangle = new RectangleObject();
        
        frame.add(aRectangle);
        frame.setVisible(true);
    }
}

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import java.awt.BasicStroke;
import java.awt.Color;
/**
 * Write a description of class RectangleObject here.
 
 */
public class RectangleObject extends JComponent
{
    public void paintComponent(Graphics g)
    {
      Graphics2D g2 = (Graphics2D) g;

      // Construct a rectangle object
      Rectangle box = new Rectangle(5, 10, 20, 30);
      // draw the rectangle
      g2.setColor(Color.red);
      g2.setStroke(new BasicStroke(5));
      g2.draw(box);  
    }
   
}

import javax.swing.JFrame;
/**
 * Draw an empty frame using JFrame.
 * 
 */

public class RectangleJFrame
{
       public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(300,400);
        frame.setTitle("A Rectanlge Object in a JFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        RectangleObject aRectangle = new RectangleObject();
        
        frame.add(aRectangle);
        frame.setVisible(true);
    }
}

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
/**
 * Write a description of class EllipseObject here.
 
 */
public class EllipseObject extends JComponent
{
    public void paintComponent(Graphics g)
    {
      Graphics2D g2 = (Graphics2D) g;

      Rectangle box = new Rectangle(100, 100, 200, 200);
      // draw the rectangle
      g2.draw(box); 
      
      // Construct an Ellipse object
      //Ellipse2D.Double circle = new Ellipse2D.Double(upperLeftXBox,upperLeftYBox , width, height);
      Ellipse2D.Double circle = new Ellipse2D.Double(100, 100, 200, 200);
      // draw the ellipse
      g2.draw(circle);
       
    }
   
}

import javax.swing.JFrame;
/**
 * Draw an empty frame using JFrame.
 * 
 */

public class EllipseJFrame
{
       public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(400,400);
        frame.setTitle("An Ellipse Object in a JFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        EllipseObject anEllipse = new EllipseObject();
        
        frame.add(anEllipse);
        frame.setVisible(true);
    }
}


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;

/*
   A component that draws an alien face
*/
public class LotsOfColors extends JComponent
{  
   public void paintComponent(Graphics g)
   {  
      // Recover Graphics2D 
      Graphics2D g2 = (Graphics2D) g;

      // Draw the an ellipse
      Ellipse2D.Double ellipse = new Ellipse2D.Double(150, 100, 100, 150);
      g2.setColor(Color.YELLOW);
      g2.draw(ellipse);

      // Draw solid green rectangle
      g2.setColor(Color.GREEN);
      Rectangle box = new Rectangle(0, 0, 50, 50);
      g2.fill(box);
      box.translate(300, 300);
      g2.fill(box);

      // Draw the mouth
      Line2D.Double line = new Line2D.Double(50, 50, 300, 300);
      g2.setColor(Color.RED);
      g2.draw(line);

      // Draw the greeting
      g2.setColor(Color.BLUE);
      g2.drawString("Some colorful shapes", 100, 100);
   }
}


import javax.swing.JFrame;
/**
 * Draw an empty frame using JFrame.
 * 
 */

public class LotsOfColorsJFrame
{
       public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(400,400);
        frame.setTitle("Shapes with lots of colors in a JFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        LotsOfColors colorfullObjects = new LotsOfColors();
        
        frame.add(colorfullObjects);
        frame.setVisible(true);
    }
}


Drawing Geometric Shapes
Screen Shot 2014-10-28 at 1.43.03 PM

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;

/**
   This component displays a circle that can be moved. 
*/
public class ShapeComponent extends JComponent
{  
   private static final int SQUARE_X = 100;
   private static final int SQUARE_Y = 100;
   private static final int SQUARE_WIDTH = 50;
   private static final int SQUARE_HEIGHT = 50;

   private Ellipse2D.Double circle;

   public ShapeComponent()
   {  
      // The rectangle that the paintComponent method draws
      circle = new Ellipse2D.Double(SQUARE_X, SQUARE_Y, SQUARE_WIDTH, SQUARE_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(circle);
   }

   /**
      Moves the rectangle to the given location.
      @param x the x-position of the new location
      @param y the y-position of the new location
   */
   public void moveTo(int x, int y)
   {
      circle = new Ellipse2D.Double(x, y, SQUARE_WIDTH, SQUARE_HEIGHT);
      repaint();      
   }
} 

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import java.awt.Color;

/**
   This program displays a ShapeComponent.
*/
public class ShapeComponentViewer
{  
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {        
      final ShapeComponent component = new ShapeComponent();

      // Add mouse press listener         

      class MousePressListener implements MouseListener
      {  
         public void mousePressed(MouseEvent event)
         {  
            int x = event.getX();
            int y = event.getY();
            component.moveTo(x, y);
         }

         // Do-nothing methods
         public void mouseReleased(MouseEvent event) {}
         public void mouseClicked(MouseEvent event) {}
         public void mouseEntered(MouseEvent event) {}
         public void mouseExited(MouseEvent event) {}
      }
         
      MouseListener listener = new MousePressListener();
      component.addMouseListener(listener);

      JFrame frame = new JFrame();
      frame.getContentPane().setBackground(new Color(255, 0, 0));
      frame.add(component);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
} 

 

input and output with a GUI

import javax.swing.JOptionPane;

/**
*  input and output with a GUI.
*/
public class InputPanel
{
   public static void main(String[] args)
   {
      String input = JOptionPane.showInputDialog("Enter a number:");
      int num = Integer.parseInt(input);
      JOptionPane.showMessageDialog(null, "The number you entered is " + num);
   }
}

 

Implementing the ActionLister with a Button

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
   An action listener that prints a message.
*/
public class ButtonListener implements ActionListener
{
   public void actionPerformed(ActionEvent event)
   {
      System.out.println("You clicked me!!!!");
   }            
}

import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
   This program demonstrates how to install an action listener.
*/
public class ButtonViewer
{  
   private static final int FRAME_WIDTH = 100;
   private static final int FRAME_HEIGHT = 60;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();
      JButton button = new JButton("Click here if you dare!");
      frame.add(button);
     
      ActionListener listener = new ButtonListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}


Screen Shot 2014-10-30 at 10.17.28 AM

 

 

Using an Inner Class:

import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
   This program demonstrates how to install an action listener.
*/
public class ButtonViewer
{  
   private static final int FRAME_WIDTH = 100;
   private static final int FRAME_HEIGHT = 60;
   

   public static void main(String[] args)
   {  
       
        /************   Inner Class Define Before is used  ***************************/
      
        /**
           An action listener that prints a message.
        */
        class ClickListener implements ActionListener
        {
           public void actionPerformed(ActionEvent event)
           {
              System.out.println("I was clicked.");
           }            
        }

       /************   Inner Class  End  ***************************/
       
       
       
       
      JFrame frame = new JFrame();
      JButton button = new JButton("Click me!");
      frame.add(button);
     
      ActionListener listener = new ClickListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      
      
      

   }
   


}


Motion effect

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/**
   This component displays a rectangle that can be moved. 
*/
public class RectangleMovingComponent extends JComponent
{  
   private static final int BOX_X = 100;
   private static final int BOX_Y = 100;
   private static final int BOX_WIDTH = 20;
   private static final int BOX_HEIGHT = 30;

   private Rectangle box;

   public RectangleMovingComponent()
   {  
      // The rectangle that the paintComponent method draws 
      box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(box);
   }

   /**
      Moves the rectangle by a given amount. 
      @param x the amount to move in the x-direction 
      @param y the amount to move in the y-direction 
   */
   public void moveBy(int dx, int dy)
   {
      box.translate(dx, dy);
      repaint();      
   }
}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

/** 	 	 	 	 	 	
   This program moves the rectangle.
*/
public class RectangleMover
{
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {
      JFrame frame = new JFrame();

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setTitle("An animated rectangle");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      final RectangleMovingComponent component = new RectangleMovingComponent();
      frame.add(component);

      frame.setVisible(true);
      
      class TimerListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            component.moveBy(1, 1);
         }
      }

      ActionListener listener = new TimerListener();

      final int DELAY = 100; // Milliseconds between timer ticks
      Timer t = new Timer(DELAY, listener);
      t.start();      
   }
}


Courtesy from Lachlan:


/* Lachlan McCarty
 * 11-16-14
 * 1.8.0_25
 * LM_MovingCar.java
 * Write a program, YI_MovingCar.java that animates a car 
 * so that it moves across a frame.
 */

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LM_MovingCar {

	private final int FRAME_WIDTH = 450;
	private final int FRAME_HEIGHT = 100;
	private final int DELAY = 100;
	private final LM_MovingCarComponent component = new LM_MovingCarComponent();
	private final JFrame frame = new JFrame();
	
	public LM_MovingCar() {
		frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
		frame.setTitle("Moving Car");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.add(component);
		
		frame.setVisible(true);
		
		ActionListener listener = new LM_TimerListener();
		Timer t = new Timer(DELAY, listener);
		t.start();
	}
	
	public static void main(String[] args) {
		new LM_MovingCar();
	}
	
	private class LM_TimerListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			component.increaseCoor(1,0);
		}
	}
	
	private class LM_MovingCarComponent extends JComponent {
		private final int MULTIPLIER = 2; //ok to change
		private int xpadding = 10; // ok to change
		private int ypadding = 10; // ok to change
		private int CAR_WIDTH = 60*MULTIPLIER; // do not change
		private int CAR_HEIGHT = 40*MULTIPLIER; // do not change
	
		public void paintComponent(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
			// turn on antialiasing so it doesn't look like crap
			RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
													RenderingHints.VALUE_ANTIALIAS_ON);
			g2.setRenderingHints(rh);
			
			g2.drawRect(0*MULTIPLIER+xpadding,10*MULTIPLIER+ypadding,60*MULTIPLIER,10*MULTIPLIER);
			g2.drawOval(10*MULTIPLIER+xpadding,20*MULTIPLIER+ypadding,10*MULTIPLIER,10*MULTIPLIER);
			g2.drawOval(40*MULTIPLIER+xpadding,20*MULTIPLIER+ypadding,10*MULTIPLIER,10*MULTIPLIER);
			g2.drawPolygon(new int[]{10*MULTIPLIER+xpadding,20*MULTIPLIER+xpadding,40*MULTIPLIER+xpadding,50*MULTIPLIER+xpadding},
							new int[]{10*MULTIPLIER+ypadding,0*MULTIPLIER+ypadding,0*MULTIPLIER+ypadding,10*MULTIPLIER+ypadding}, 4);
		}
		
		public void increaseCoor(int x, int y) {
			if (xpadding+x+CAR_WIDTH <= FRAME_WIDTH) xpadding += x;
			if (ypadding+y+CAR_HEIGHT <= FRAME_HEIGHT) ypadding += y;
			repaint();
		}
	}
}

Screen Shot 2014-11-25 at 1.43.16 PM

 

Concepts and theory:

Java Applets: Frames and Panels

A frame is a container that is used to display GUI-based Java applications.
A frame is displayed as a separate window with its own title bar.
It can be repositioned on the screen and re-sized as needed by dragging it with the mouse.
It contains small buttons in the corner of the frame that allow the frame to be minimized, maximized, and closed.
A frame is defined by the JFrame class.
A panel is also a container. However, unlike a frame, it cannot be displayed on its own.
A panel must be added to another container for it to be displayed.
Generally a panel doesn’t move unless you move the container that it’s in.
Its primary role is to help organize the other components in a GUI.
A panel is defined by the JPanel class.


Java Applets: Components and Containers

A GUI component is an object that represents a screen element that is used to display information or to allow the user to interact with the program in a certain way.
A container is a special type of component that is used to hold and organize other components.
Frames and panels are two examples of Java containers.