问题描述
测试鼠标的事件响应,但是没反应。下面是代码import javax.swing.*;import java.awt.event.*;import java.awt.BorderLayout;public class TestMouseMotion implements MouseListener {/** * 测试底层鼠标事件 */int flag;//响应事件的标识;JFrame mf = new JFrame("鼠标事件测试");JLabel g_m_label = new JLabel("鼠标测试!", SwingConstants.RIGHT);public TestMouseMotion(){flag = 7;mf.setBounds(100, 100, 300, 200);//BorderLayout mf_layout = new BorderLayout();//mf.setLayout(mf_layout);mf.getContentPane().add(g_m_label, BorderLayout.SOUTH);if (flag == 0){mf.add(new JLabel("鼠标放在了面板上!", SwingConstants.CENTER));}else if(flag == 1){mf.add(new JLabel("鼠标点击了面板!", SwingConstants.CENTER));}else if (flag == 2){mf.add(new JLabel("鼠标离开了面板!", SwingConstants.CENTER));}mf.setResizable(false);mf.setVisible(true);}public static void main(String[] args) {new TestMouseMotion();}public void mousePressed(MouseEvent me) {}public void mouseReleased(MouseEvent me) {}public void mouseClicked(MouseEvent me) {flag = 0;}public void mouseEntered(MouseEvent me) {flag = 1;}public void mouseExited(MouseEvent me) {flag = 2;}}由于是自学,基础不扎实,swing的事件响应和框架面板一团浆糊。希望有人帮忙,谢谢。 问题补充:jkxydp 写道
解决方案
你没有绑定事件,调用要监听的组件上的addMouseListener(this),参数是this的原因是 你的TestMouseMotion 本身实现了MouseListener接口。你可以在构造函数里面加上一句:addMouseListener(this);然后在public void mouseClicked(MouseEvent me) { System.out.println("窗口被点击了"); }