简体   繁体   English

JPanel / JDialog中的mouseLIstener“不起作用”

[英]mouseLIstener “not working” in JPanel/JDialog

Since my previous post was a mess, I decided to repost it but hopefully much cleaner this time. 由于我的前一篇文章一团糟,我决定重新发布,但希望这次更加干净。

So here is the code I'm trying to work with: 因此,这是我尝试使用的代码:

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

public class sample extends JFrame implements ActionListener, MouseListener
{
        JButton b1, b2;
        JPanel panel1;
        JDialog dialog;


public sample()
{
    dialog = new JDialog();
    dialog.setBounds (0,0,200,200);

    panel1 = new JPanel();
    panel1.setLayout (new FlowLayout());

    b1 = new JButton("B1");
    add(b1);
    b1.addActionListener (this);
    b1.addMouseListener (this);

    b2 = new JButton ("B2");
    panel1.add(b2);
    b2.addMouseListener (this);
    dialog.add(panel1);

             /* I tried this but it didn't work as well:
             dialog.addMouseListener(this);
             panel1.addMouseListener(this); */
    }

    public void actionPerformed (ActionEvent e)
    {
    if (e.getSource () == b1)
        {
            dialog.setVisible (true);
        }
    }

    public void mouseClicked (MouseEvent e)
    {

    }
    public void mouseEntered (MouseEvent e)
    {
        setCursor (new Cursor (Cursor.HAND_CURSOR));
    }
    public void mouseExited (MouseEvent e)
    {
        setCursor (new Cursor(Cursor.DEFAULT_CURSOR));
    }
   public void mousePressed (MouseEvent e)
    {
    }
    public void mouseReleased (MouseEvent e)
    {
    }

    public static void main (String[] args) {
    sample s = new sample();
    s.setVisible (true);
    s.setBounds (0,0,200,200);
}
}

My goal is for the cursor to change to the hand cursor when the user hovers over B2, but it doesn't. 我的目标是当用户将鼠标悬停在B2上时将光标更改为手形光标,但事实并非如此。 What am I missing? 我想念什么?

Your problem in next: 接下来的问题:

You set Cursor to sample instance( JFrame ), not to JButton , for setting cursor on button change setCursor (new Cursor (Cursor.HAND_CURSOR)); 您将Cursor设置为sample实例( JFrame ),而不是JButton ,以将光标设置在按钮更改setCursor (new Cursor (Cursor.HAND_CURSOR)); to ((JComponent)e.getSource()).setCursor (new Cursor (Cursor.HAND_CURSOR)); ((JComponent)e.getSource()).setCursor (new Cursor (Cursor.HAND_CURSOR));

Also for that purposes you needn't to use MouseListener you can just use: 同样出于此目的,您无需使用MouseListener即可使用:

b1.setCursor(new Cursor (Cursor.HAND_CURSOR));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM