我試圖編寫關於mouselistener的程序。我想製作程序,如果鼠標光標進入或退出框架,框架的背景顏色會發生變化。背景顏色變化Java
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
public class EnterExitListener extends JFrame
{
public static void main(String [] args)
{
JFrame frame=new JFrame();
final int FRAME_WIDTH=500;
final int FRAME_HEIGHT=600;
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
class MouseEnterExitListener implements MouseListener
{
public void mouseEntered(MouseEvent event)
{
System.out.println("ENTER");
frame.setBackground(Color.BLUE);
}
public void mouseExited(MouseEvent event)
{
System.out.println("EXIT");
frame.setBackground(Color.RED);
}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mousePressed(MouseEvent event) {}
}
MouseListener listener = new MouseEnterExitListener();
frame.addMouseListener(listener);
}
}
編譯沒有問題,如果我運行程序,它顯示ENTER,EXIT在I/O消息。但問題是顏色不變。它根本就是白色的框架。
爲什麼要擴展JFrame?你的代碼創建一個JFrame,所以不需要擴展JFrame。 – camickr