Java在鼠标悬停时重新绘制组件。 [英] Java repainting a component at mouse-over.

查看:154
本文介绍了Java在鼠标悬停时重新绘制组件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作我的第一个正确定制的GUI,但我很难更改为组件绘制的图像。基本上,对于我的exitButton(一个JMenu),我覆盖了paint方法,然后添加了一个Mouse监听器,但我不确定如何在鼠标输入方法中重新绘制mouseListener接口内的图像,并再次在鼠标退出方法中重新绘制。基本上我正在寻找一种重新绘制图像的方法,但我迷失了我能做什么。任何帮助将不胜感激。



以下是相关的代码段:

  exitBtn = new JMenu(){
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon exitBtnImg = new ImageIcon(src / images / userInterface / exitBtn.gif);
g.drawImage(exitBtnImg.getImage(),0,5,null);
}
};
exitBtn.setOpaque(false);
exitBtn.setEnabled(false);
exitBtn.setPreferredSize(new Dimension(43,18));
exitBtn.addMouseListener(new MouseListener(){
@Override
public void mousePressed(MouseEvent me){
}
@Override
public void mouseClicked( MouseEvent me){
System.exit(0);
}
@Override
public void mouseEntered(MouseEvent me){
// ImageIcon exitBtnImg = new ImageIcon( src / images / exitBtn_hover.gif); //我想使用的ImageIcon
System.out.println(鼠标输入);

}
@Override
public void mouseExited(MouseEvent me){
// ImageIcon exitBtnImg = new ImageIcon(src / images / exitBtn.gif);

System.out.println(mouse exited); //原始图像的imageicon
}
@Override
public void mouseReleased(MouseEvent me){
}
});

解决方案


我正在尝试制作我的第一个正确定制的GUI


您应该首先阅读Swing教程。我不确定你要做什么,但你的做法肯定是错误的。



你可以从如何使用菜单,显示如何使用ActionListener处理鼠标单击。鼠标点击通常在菜单项上处理,而不是在菜单上处理。你通常会有类似文件菜单的东西,它包含一个退出菜单项。



然后我还会看一下JMenu API的各种允许的方法您可以在鼠标悬停或选择菜单时更改图标。也许setRolloverEnabled(),setRolloverIcon()就是你要找的。

如果你还有问题,那么发一个 SSCCE 证明了这个问题。



更新:



如Hovercraft所述,翻转支持不适用于菜单或菜单项。有两个问题。首先,这些组件使用不同的MouseListener。侦听器不侦听mouseEntered和mouseExited事件。第二个问题是两个组件的UI已经自定义,自定义图标绘制代码没有考虑按钮的翻转状态。



添加MouseListener简单。自定义UI(这是正确的解决方案)以更好地支持翻转更为复杂。



对于一个似乎有效的简单hack,我只是更新MouseListener中的Icon,而不是让UI确定要绘制哪个Icon。我建议你忘记这个要求并使用普通的UI,它不会改变菜单和菜单项的图标。使用以下风险需要您自担风险:

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

公共类ButtonRollover扩展JFrame
{
图标正常;
图标翻转;
图标已选中;

public ButtonRollover()
{
MouseListener ml = new RolloverButtonListener();

normal = new ColorIcon(Color.GREEN,10,10);
rollover = new ColorIcon(Color.RED,10,10);
selected = new ColorIcon(Color.BLUE,10,10);

setLayout(new FlowLayout());

JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

JMenu menu =(JMenu)createButton(new JMenu(),Menu);
menu.addMouseListener(ml);
menuBar.add(menu);

JMenuItem menuItem =(JMenuItem)createButton(new JMenuItem(),MenuItem);
menuItem.addMouseListener(ml);
menu.add(menuItem);

JButton button =(JButton)createButton(new JButton(),Button);
add(button);

JCheckBox checkBox =(JCheckBox)createButton(new JCheckBox(),CheckBox);
add(checkBox);

JRadioButton radioButton =(JRadioButton)createButton(new JRadioButton(),RadioButton);
add(radioButton);
}


public AbstractButton createButton(AbstractButton button,String text)
{
button.setText(text);
button.setIcon(normal);
button.setSelectedIcon(已选中);
button.setRolloverIcon(rollover);
button.setRolloverSelectedIcon(rollover);

System.out.println(text);
MouseListener [] mls = button.getMouseListeners();

for(MouseListener ml:mls)
{
System.out.println(\t+ ml);
}

返回按钮;
}

类RolloverButtonListener扩展MouseAdapter
{
private Icon normal;

public void mouseEntered(MouseEvent e)
{
AbstractButton b =(AbstractButton)e.getSource();
ButtonModel model = b.getModel();

if(b.isRolloverEnabled()&&!SwingUtilities.isLeftMouseButton(e))
{
normal = b.getIcon();
b.setIcon(b.getRolloverIcon());
model.setRollover(true);
}
}

public void mouseExited(MouseEvent e)
{
AbstractButton b =(AbstractButton)e.getSource();
ButtonModel model = b.getModel();

if(b.isRolloverEnabled())
{
b.setIcon(normal);
model.setRollover(false);
}
};

}

公共类ColorIcon实现Icon
{
private color color;
private int width;
private int height;

public ColorIcon(Color color,int width,int height)
{
this.color = color;
this.width = width;
this.height = height;
}

public int getIconWidth()
{
返回宽度;
}

public int getIconHeight()
{
返回高度;
}

public void paintIcon(Component c,Graphics g,int x,int y)
{
g.setColor(color);
g.fillRect(x,y,width,height);
}
}

public static void main(String [] args)
{
try
{
// UIManager .setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(例外e){}

ButtonRollover frame = new ButtonRollover();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(400,200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}


I am attempting to make my first properly customised GUI, but I am having difficulty changing the image which has been painted for a component. Basically, for my exitButton (a JMenu) I overwrite the paint method, and then add a Mouse listener, but I am not sure how to repaint the image within the mouseListener interface in the Mouse entered method and again in the mouse exited method. Essentially I am looking for a way to repaint the image, but I am lost as to what I can do. Any help would be greatly appreciated.

Here is the relevant code snippet:

exitBtn = new JMenu(){
       @Override
       protected void paintComponent(Graphics g) {
        super.paintComponent(g);
           ImageIcon exitBtnImg = new ImageIcon("src/images/userInterface/exitBtn.gif");
           g.drawImage(exitBtnImg.getImage(), 0, 5, null);
      }
  };
  exitBtn.setOpaque(false);
  exitBtn.setEnabled(false);
  exitBtn.setPreferredSize(new Dimension(43, 18));
  exitBtn.addMouseListener(new MouseListener() {
        @Override
        public void mousePressed(MouseEvent me) {
        }
        @Override
        public void mouseClicked(MouseEvent me) {
            System.exit(0);
        }
        @Override
        public void mouseEntered(MouseEvent me) {
            //ImageIcon exitBtnImg = new ImageIcon("src/images/exitBtn_hover.gif"); //The ImageIcon for the Image I want to use
            System.out.println("mouse entered");

        }
        @Override
        public void mouseExited(MouseEvent me) {
            // ImageIcon exitBtnImg = new ImageIcon("src/images/exitBtn.gif"); 

System.out.println("mouse exited"); // The imageicon for the origianl image } @Override public void mouseReleased(MouseEvent me) { } });

解决方案

I am attempting to make my first properly customised GUI

You should start by reading the Swing tutorial. I'm not really sure what you are trying to do but your approach sure seems wrong.

You can start with How to Use Menus which shows how to use an ActionListener to handle a mouse click. Mouse clicks are generally handled on a menu item, not a menu. You would generally have something like a "File" menu that wouuld contain an "Exit" menu item.

Then I would also look at the JMenu API for various methods that allow you to change the Icon when you mouse over or select a menu. Maybe setRolloverEnabled(), setRolloverIcon() is what you are looking for.

If you still have problems, then post a SSCCE that demonstrates the problem.

Update:

As mentioned by Hovercraft, rollover support does not work for menus or menu items. There are two problems. First of all a different MouseListener is used by these components. The listener does NOT listen for mouseEntered and mouseExited events. The second problem is that the UI for the two components has been customized and the custom Icon painting code does not take into account the rollover state of the button.

Adding a MouseListener is easy. Customizing the UI (which is the proper solution) to properly support rollovers is more involved.

For a simple hack that seems to work, I just update the Icon in the MouseListener rather than having the UI determine which Icon to paint. I advise you to forget about this requirement and use a normal UI which does not change Icons for menus and menu items. Use the following at your own risk:

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

public class ButtonRollover extends JFrame
{
    Icon normal;
    Icon rollover;
    Icon selected;

    public ButtonRollover()
    {
        MouseListener ml = new RolloverButtonListener();

        normal = new ColorIcon(Color.GREEN, 10, 10);
        rollover = new ColorIcon(Color.RED, 10, 10);
        selected = new ColorIcon(Color.BLUE, 10, 10);

        setLayout( new FlowLayout() );

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar( menuBar );

        JMenu menu = (JMenu)createButton(new JMenu(), "Menu");
        menu.addMouseListener( ml );
        menuBar.add( menu );

        JMenuItem menuItem = (JMenuItem)createButton(new JMenuItem(), "MenuItem");
        menuItem.addMouseListener( ml );
        menu.add( menuItem );

        JButton button = (JButton)createButton(new JButton(), "Button");
        add( button );

        JCheckBox checkBox = (JCheckBox)createButton(new JCheckBox(), "CheckBox");
        add( checkBox );

        JRadioButton radioButton = (JRadioButton)createButton(new JRadioButton(), "RadioButton");
        add( radioButton );
    }


    public AbstractButton createButton(AbstractButton button, String text)
    {
        button.setText( text );
        button.setIcon( normal );
        button.setSelectedIcon( selected );
        button.setRolloverIcon( rollover );
        button.setRolloverSelectedIcon( rollover );

        System.out.println( text );
        MouseListener[] mls = button.getMouseListeners();

        for (MouseListener ml: mls)
        {
            System.out.println( "\t" + ml);
        }

        return button;
    }

    class RolloverButtonListener extends MouseAdapter
    {
        private Icon normal;

        public void mouseEntered(MouseEvent e)
        {
            AbstractButton b = (AbstractButton) e.getSource();
            ButtonModel model = b.getModel();

            if (b.isRolloverEnabled() && !SwingUtilities.isLeftMouseButton(e))
            {
                normal = b.getIcon();
                b.setIcon(b.getRolloverIcon());
                model.setRollover(true);
            }
        }

        public void mouseExited(MouseEvent e)
        {
            AbstractButton b = (AbstractButton) e.getSource();
            ButtonModel model = b.getModel();

            if(b.isRolloverEnabled())
            {
                b.setIcon( normal );
                model.setRollover(false);
            }
        };

    }

    public class ColorIcon implements Icon
    {
        private Color color;
        private int width;
        private int height;

        public ColorIcon(Color color, int width, int height)
        {
            this.color = color;
            this.width = width;
            this.height = height;
        }

        public int getIconWidth()
        {
            return width;
        }

        public int getIconHeight()
        {
            return height;
        }

        public void paintIcon(Component c, Graphics g, int x, int y)
        {
            g.setColor(color);
            g.fillRect(x, y, width, height);
        }
    }

    public static void main(String[] args)
    {
        try
        {
//          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) { }

        ButtonRollover frame = new ButtonRollover();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(400, 200);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

这篇关于Java在鼠标悬停时重新绘制组件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆