简体   繁体   English

未修饰的按钮:带有MouseListener的JButton或JLabel?

[英]Undecorated button: JButton or JLabel with MouseListener?

I want to implement a button that does not show borders or anything else, except for an image that changes when you hover over it. 我想要实现一个不显示边框或其他任何东西的按钮,除了将鼠标悬停在其上时会更改的图像。 Clicking on the image (showing the hover image) will execute some code. 单击图像(显示悬停图像)将执行一些代码。

I also would like to put all this in a separate class so I have a reusable component. 我还想将所有这些都放在一个单独的类中,以便我有一个可重用的组件。

Extending a JButton delivers me the methods addActionListener() and so forth. 扩展JButton为我提供了addActionListener()等方法。 But using the setAction() method removes the images that I set in the constructor. 但是使用setAction()方法会删除我在构造函数中设置的图像。 So it's not watertight, as I cannot use an Action in combination with this class. 因此它不是水密的,因为我不能将Action与此类结合使用。 And I certainly do not want to override method like setAction(). 而且我当然不想覆盖setAction()之类的方法。

public class JHoverLabel extends JButton {

private final Icon normal;
private final Icon hovered;

public JHoverLabel (Icon normal, Icon hovered) {
    this.normal = normal;
    this.hovered = hovered;

    setIcon(normal);

    setFocusPainted(false);
    setMargin(new Insets(0, 0, 0, 0));
    setContentAreaFilled(false);
    setBorderPainted(false);
    setOpaque(false);

    addMouseListener(new HoverListener());
}


private class HoverListener implements MouseListener {

    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {
        setIcon(hovered);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        setIcon(normal);
    }

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseReleased(MouseEvent e) {}        
} 
}

Extending a JLabel seems to do what a want in combination with a MouseListener, but I feel like using the wrong component here, because 'click-on-me-to-do-something' basically leads me to a JButton. 扩展JLabel似乎可以与MouseListener结合使用,但是我感觉这里使用了错误的组件,因为“按我做某事”基本上使我使用了JButton。

So what should I use? 那我该怎么用呢? A JLabel or a JButton? JLabel还是JButton?

use implemented methods for JButton.setXxxIcon JButton.setXxxIcon使用已实现的方法

button.setRolloverIcon((Icon));
button.setPressedIcon(Icon);
button.setDisabledIcon(Icon);

instead of MouseListener you can implements ButtonModel 代替MouseListener您可以实现ButtonModel

So what should I use? 那我该怎么用呢? A JLabel or a JButton? JLabel还是JButton?

Use a JButton . 使用JButton Your mouse challenged users will thank you. 您的鼠标挑战用户将感谢您。

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

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