Search This Blog

Monday, February 20

!ANSWER! Assignment 5


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.
   * An object of an anonymous inner class that implements Runnable
   * interface is sent to event dispatching thread which executes the run
   * method.
  new Runnable() {

   public void run() {

    // construct a JFrame object
    Drawing frame = new Drawing();
    // set the new JFrame to be visible
    // exit program when the JFrame is closed

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

 public Drawing() {
  //sets name & size of window
  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()
   public void paint(Graphics g) {  //is responsible for drawing the users motions on the content pane

No comments:

Post a Comment