Making a drawing application using swing and mouse listener

时间:2015-10-29 15:52:45

标签: java swing

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

1 个答案:

答案 0 :(得分:3)

你老师的源代码非常糟糕,因为你永远不应该在绘画方法或JFrame中绘图,加上他/她的绘画覆盖不会调用超级方法,打破绘画链。他们似乎不知道他们在做什么。

话虽如此,您的主驱动程序不应该扩展JFrame,也不应该尝试创建它的JFrame甚至是它的实例。相反,在这个类的main方法中,创建一个可怕的绘图类的实例。

请注意,我不明白这个要求:

  

和最后一个绘图。

请发布完全要求。

如果这是我的申请,我会

  • 在JPanel中绘制我的绘图,而不是JFrame
  • 在JPanel的paintComponent方法中进行,而不是绘制方法。
  • 请务必在我的JPanel的paintComponent方法覆盖中调用超级paintComponent方法。
  • 然后将我的JPanel放在JFrame中以显示它。
  • 我不会让我的GUI类实现MouseListener,而是使用嵌套的内部类。