Search This Blog

Monday, February 20

!ANSWER! Assignment 5

...and...

WE ARE DONE!
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class BajrovicAssignment5 {
 
 public static void main(String[] args) {

  // Swing is not thread safe.
  // UI code should run in a event dispatching thread.
  EventQueue.invokeLater(
  /**
   * An object of an anonymous inner class that implements Runnable
   * interface is sent to event dispatching thread which executes the run
   * method.
   */
  new Runnable() {

   @Override
   public void run() {

    // construct a JFrame object
    Drawing frame = new Drawing();
    // set the new JFrame to be visible
    frame.setVisible(true);
    // exit program when the JFrame is closed
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
  });
 }
}


class Drawing extends JFrame {
private JLabel coordinates;
private int x=0, y=0;
private Color color;

 public Drawing() {
  //sets name & size of window
  setTitle("BajrovicAssignment5");
  setSize(500, 200);
  
  // add the panel to the content pane of the JFrame
  
  coordinates = new JLabel();
  Container contentPane = getContentPane();
  contentPane.add(coordinates, BorderLayout.SOUTH);
    
  contentPane.addMouseMotionListener(new mouseMovements());  //records user's motions on content pane
 }
   class mouseMovements extends MouseMotionAdapter{
    public void mouseMoved(MouseEvent e) {  //added functionality just for clarity 
     coordinates.setText("X: " + Integer.toString(e.getX()) + ", Y: " + Integer.toString(e.getY()));
   }
    public void mouseDragged(MouseEvent e) {
     x = e.getX(); //gets the current x & y coordinates of mouse, updated as mouse is dragged
        y = e.getY();
     repaint();  //neater to use than update() or paint()
    }
   }
   public void update(Graphics g){ //added for clarity for the repaint method, b/c the repaint method first calls update() THEN paint()
     paint(g);
    }
    
   public void paint(Graphics g) {  //is responsible for drawing the users motions on the content pane
     g.setColor(Color.black);
     g.fillRect(x,y,10,10);
    }
     }

No comments:

Post a Comment