Making a drawing application using swing and mouse listener

i have an assignment to make a simple drawing application using swing and mouse listener. the application has to have three classes, one that contains Main, one that contains the frame, and the last one that makes the drawing. The teacher gave us a source code we're supposed to use to complete the assignment and it looks like this:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;

public class Drawsome extends JFrame implements MouseMotionListener {


public Drawsome(){
    setSize(300,400);
    setForeground(Color.black);     
    show();;
    addMouseMotionListener(this);
}



 public void mouseDragged(MouseEvent evt) {
   start = end;
   end = new Point(evt.getX(),evt.getY());
   repaint();
 }

 public void mouseMoved(MouseEvent evt) {  
  end = null;
 }

 public void paint(Graphics g) {
     if (start!=null  && end!=null)
     g.drawLine(start.x, start.y, end.x, end.y);

 }


 public void update(Graphics g) {
     paint(g);
 }


Point start=null;
Point end=null;

}

now this work perfectly, but since we have to make the frame in another class i tried to do this:

import java.awt.Color;
import javax.swing.JFrame;

public class MainWindow extends JFrame {

    public  MainWindow() {

        setSize(300,400);
        setForeground(Color.black);     
        show();;        

    }

}


import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;

public class Drawsome extends JFrame implements MouseMotionListener {


public Drawsome(){
MainWindow mainwindow = new MainWindow();

addMouseMotionListener(this);
} (rest is the same as the previous code)

i'll get a frame, but the rest doesn't work, i dont' understand what i'm doing wrong, and would greatly appreciate a push in the right direction

Upvotes: 0

Views: 736

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your teacher's source code is terrible since you should never be drawing within the paint method or within a JFrame, plus his/her paint override doesn't call the super's method, breaking the painting chain. They don't appear to know what they're doing.

Having said that, your main driver should not extend JFrame nor should you try to create a JFrame of it or even an instance of it. Instead, in this class's main method, create an instance of the terrible drawing class.

Note that I don't understand this requirement:

and the last one that makes the drawing.

Please post the exact requirements.


If this were my application, I'd

  • Do my drawing within a JPanel, and not a JFrame
  • Do it within the JPanel's paintComponent method, not the paint method.
  • Be sure to call the super's paintComponent method within my JPanel's paintComponent method override.
  • Then place my JPanel within a JFrame to display it.
  • I would not have my GUI class implement the MouseListener but rather would use a nested inner class for this.

Upvotes: 3

Related Questions