如何将悬停效果放在jbutton上?

use*_*343 7 java swing rollover jbutton mouselistener

我正在尝试创建一个Java桌面应用程序,我使用两个按钮.我想在这些按钮中添加悬停效果.我想:当我点击任何按钮时,它应该改变它的背景颜色.

我怎样才能实现它?

这是我的代码:

public class Party1Party2 extends JFrame
{
    JButton b1;
    JButton b2;
    Container pane;

    public Party1Party2()
    {
        getContentPane().setBackground(new java.awt.Color(255, 255, 255));

    b2.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            JOptionPane.showMessageDialog(frame, "Welcome to allhabad High Court");
        }
    });

    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            JOptionPane.showMessageDialog(frame, "Welcome to allhabad High Court");

        }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Sal*_*lah 16

你可以使用moused EnteredExitedthe JButton,并做你想做的事.

例如:

jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        jButton1.setBackground(Color.GREEN);
    }

    public void mouseExited(java.awt.event.MouseEvent evt) {
        jButton1.setBackground(UIManager.getColor("control"));
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 哦,eeeeasy,我认为你试图说有一个更好的方法来做到这一点,但这不是一个错误的答案,至少对我来说,因为我多次这样做,请在你的评论中更现代! ! (9认同)
  • 这个讨论如果没有,特别是因为缺乏对"更好"的想法的提及.我在这里找到了它:http://stackoverflow.com/questions/16733708/changing-value-of-boolean-when-mouse-cursor-hovers-over-a-jbutton/16733866#16733866 (3认同)
  • 答案是错误的,所有鼠标事件都是在 JButtons API 中实现的,并正确使用它们而不是鼠标侦听器 (2认同)
  • 好的,那么请在下次明确表示您想要编辑我的答案或者注意到使用其他东西时有更好的方法,当您说"忽略那些答案"时,您在之前的评论中并不清楚"答案是错的",谢谢你的提示,不好更新我的回答. (2认同)