由于我之前的帖子很乱,我决定重新发布,但希望这次更清洁。
所以这是我正在尝试使用的代码:
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);
}
}
我的目标是当用户将鼠标悬停在B2上时光标变为手形光标,但事实并非如此。 我错过了什么?
答案 0 :(得分:3)
下一步你的问题:
您将光标设置为sample
实例(JFrame
),而不是JButton
,将按钮更改setCursor (new Cursor (Cursor.HAND_CURSOR));
上的光标设置为((JComponent)e.getSource()).setCursor (new Cursor (Cursor.HAND_CURSOR));
此外,您无需使用MouseListener
即可使用:
b1.setCursor(new Cursor (Cursor.HAND_CURSOR));