import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.event.*;
public class MouseAct extends JFrame{
public static void main(String args[]){
MouseAct M= new MouseAct();
M.paint1();
}
public void paint1(){
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize(640,480); //
show();
}
public void paint( Graphics g ){
super.paint(g);
Graphics2D g2=(Graphics2D)g;
g.setColor(Color.black);
g.fillRect(1,1,638,478);
g.setColor(Color.white);
g.drawRect(1,1,638,478);
g.drawRect(100,100,100,100);
MouseListener l = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
MouseAct b = (MouseAct)e.getSource();
System.out.println("source="+e.getSource());
// b.setSelected(true);
b.repaint();
}
public void mouseReleased(MouseEvent e) {
MouseAct b = (MouseAct)e.getSource();
// b.setSelected(false);
b.repaint();
}
};
}
// public void setSelected(){
}
最佳答案
(1)不要在paint方法内创建Mouselistener-现在在每次重绘上创建一个新的Mouselistener。在paint1()
里面会更好
(2)将侦听器添加到MouseAct对象。然后,当指针在框架上方时,只要按下鼠标按钮,就会调用该方法。
public void paint1(){
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize(640,480);
MouseListener l = new MouseAdapter() { ... } // add your code here
addMouseListener(l); // this 'activates' the listener
show();
}