2011-10-30 65 views
0

我想在矩形外側單擊鼠標時更改背景顏色。我只是不知道如何使用MouseEvent。更改鼠標事件的背景顏色

import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 

public class AnAppletWithMouseEvents extends Applet implements MouseListener { 
public void init() 
{ 
    addMouseListener(this); 
} 
public void paint(Graphics g) 
{ 

    g.setColor(Color.green); 
    g.drawRect(10, 30, 150, 150); 
} 
public void mouseClicked(MouseEvent e) 
{ 
    String clickDesc; 
    if (e.getClickCount() == 2) 
     clickDesc = "double"; 
    else 
     clickDesc = "single"; 

    System.out.println("Mouse was " + clickDesc + "-clicked at location (" + 
     e.getX() + ", " + e.getY() + ")"); 

} 
public void mouseEntered(MouseEvent e) {} 
public void mouseExited(MouseEvent e) {} 
public void mousePressed(MouseEvent e) {} 
public void mouseReleased(MouseEvent e) {} 
} 
+1

那麼你的問題是什麼?當你點擊任何地方時,輸出是什麼? – Sibbo

+1

究竟是什麼部分你有麻煩?你的'mouseClicked'方法工作嗎?如果是這樣,你有點鼠標點和矩形的邊界,你還需要什麼? – Kevin

回答

0
import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 

public class AnAppletWithMouseEvents extends Applet implements MouseListener { 
Color color = Color.green; 
public void init() 
{ 
    addMouseListener(this); 
} 
public void paint(Graphics g) 
{ 

    g.setColor(this.color); 
    g.drawRect(10, 30, 150, 150); 
} 
public void mouseClicked(MouseEvent e) 
{ 
    this.color = color.red; 
    this.repaint(); 

} 
public void mouseEntered(MouseEvent e) {} 
public void mouseExited(MouseEvent e) {} 
public void mousePressed(MouseEvent e) {} 
public void mouseReleased(MouseEvent e) {} 
} 

現在你需要計算,如果點擊是矩形的界限之外。

+0

當然,您還應該添加一個檢查來查看點擊是否在矩形內。但是鑑於操作系統的原始代碼,他應該知道如何去做。 –

0

mouseClicked方法,你應該測試e.getX()e.getY()是矩形之外,然後調用setBackground()

this.setBackground(Color.red);

的矩形邊框將保持綠色(就是你想要什麼?)

HTH