2008-08-29 57 views
6

所以,我已經有了一個JPanel實施MouseListenerMouseMotionListener我(的Java/Swing的)的MouseListener就是不聽,幫我弄清楚爲什麼

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

public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener { 
    public DisplayArea(Rectangle bounds, Display display) { 
     setLayout(null); 
     setBounds(bounds); 
     setOpaque(false); 
     setPreferredSize(new Dimension(bounds.width, bounds.height)); 

     this.display = display; 
    } 

    public void paintComponent(Graphics g) { 
     Graphics2D g2 = (Graphics2D)g; 
     if (display.getControlPanel().Antialiasing()) { 
      g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); 
     } 
     g2.setColor(Color.white); 
     g2.fillRect(0, 0, getWidth(), getHeight()); 
    } 

    public void mousePressed(MouseEvent event) { 
     System.out.println("mousePressed()"); 
     mx1 = event.getX(); 
     my1 = event.getY(); 
    } 

    public void mouseReleased(MouseEvent event) { 
     System.out.println("mouseReleased()"); 
     mx2 = event.getX(); 
     my2 = event.getY(); 

     int mode = display.getControlPanel().Mode(); 
     switch (mode) { 
     case ControlPanel.LINE: 
      System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + "."); 
     } 
    } 

    public void mouseEntered(MouseEvent event) { 
     System.out.println("mouseEntered()"); 
    } 

    public void mouseExited(MouseEvent event) { 
     System.out.println("mouseExited()"); 
    } 

    public void mouseClicked(MouseEvent event) { 
     System.out.println("mouseClicked()"); 
    } 

    public void mouseMoved(MouseEvent event) { 
     System.out.println("mouseMoved()"); 
    } 

    public void mouseDragged(MouseEvent event) { 
     System.out.println("mouseDragged()"); 
    } 

    private Display display = null; 

    private int mx1 = -1; 
    private int my1 = -1; 
    private int mx2 = -1; 
    private int my2 = -1; 
} 

麻煩的是,沒有這些鼠標功能是以往任何時候都調用。 DisplayArea創建這樣的:

da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this); 

我不是一個真正的Java程序員(這是任務的一部分),但我看不到任何東西昭然若揭。有人能比我看到什麼更聰明嗎?

回答

13

實現了mouselistener,mousemotionlistener只是允許displayArea類監聽Swing組件的鼠標事件。你必須明確地定義它應該聽什麼。所以,我想你會喜歡這個東西添加到構造函數:

this.addMouseListener(this); 
this.addMouseMotionListener(this); 
3

我看不出在你調用addMouseListener將(本)或addMouseMotionListener(本)爲DisplayArea以便其認購代碼的任何地方到那些事件。

3

我在這裏沒有看到任何代碼註冊到鼠標監聽器。您必須在DisplayArea上調用addMouseListener(this)和addMouseMotionListener(this)。

相關問題