当前位置: 代码迷 >> J2SE >> 实现了鼠标的监听器类为什么没有反应呢?解决方法
  详细解决方案

实现了鼠标的监听器类为什么没有反应呢?解决方法

热度:19   发布时间:2016-04-24 01:03:04.0
实现了鼠标的监听器类为什么没有反应呢?
package test;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.text.html.HTMLDocument.Iterator;

public class TestDrawLine extends JPanel implements MouseMotionListener ,MouseListener
{
public TestDrawLine()
{



}
private List<Point> pointList = new ArrayList<Point>();


@Override
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
Point p = new Point();
p.setX(x);
p.setY(y);
pointList.add(p);

System.out.println(x);
System.out.println(y);


}


@Override
public void mouseDragged(MouseEvent e) 
{
int x = e.getX();
int y = e.getY();
Point p1 = new Point();
p1.setX(x);
p1.setY(y);
pointList.add(p1);
System.out.println("welcome");
System.out.println("nihao");

}

@Override
public void mouseClicked(MouseEvent e) {

System.out.println("hahaha");

}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}
public void mouseExited(MouseEvent e) 
{



}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub

}



@Override
public void mouseReleased(MouseEvent e) {









}

@Override
protected void paintComponent(Graphics g) {

super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;

Line2D l2 = new Line2D.Double(50,50,400,400);

g2.draw(l2);

System.out.println("helloworld");



}





}

   


}


包含主方法的类:
package test;

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;

public class TestFrame extends JFrame
{

public static void main(String[]args)
{

TestFrame tf = new TestFrame();
TestDrawLine tdl = new TestDrawLine();
tdl.setBackground(Color.WHITE);
tf.setSize(new Dimension(500,500));
tf.add(tdl);
tf.setBackground(Color.WHITE);
tf.setVisible(true);




}




}

运行这个主方法之后,出现了一个frame,上面出现了一条直线,但是我点击面板,却没有输出"welcom"和“你好”在控制台上,只输出了,“helloworld”,请问,问题出在哪里呢?多谢了!





------解决方案--------------------
这是因为你没有加事件监听!
在主方法中加这句:tdl.addMouseListener(tdl);
------解决方案--------------------
public TestDrawLine() {

}
==》
public TestDrawLine() {
addMouseMotionListener(this);
addMouseListener(this);
}
  相关解决方案