Java 在 Jlabel 上实现简单的悬停效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20835173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:40:39  来源:igfitidea点击:

Implementing a simple hover effect on a Jlabel

javaswingcolorsjlabelmouselistener

提问by JME

I am messing around with some ideas for a side project and I would like to create a GUI using Java swing that doesn't look like it is from Windows95. One of the ideas I was kicking around was to use JLabels as buttons instead of the standard JButton. This would allow me to customize hover, drag, and movement effects as I like.

我正在为一个副项目考虑一些想法,我想使用 Java swing 创建一个 GUI,它看起来不像来自 Windows95。我的想法之一是使用 JLabels 作为按钮而不是标准的 JButton。这将允许我根据自己的喜好自定义悬停、拖动和移动效果。

Research into the MouseAdapter classshould allow me to do everything I intend, unfortunately I am having some trouble implementing the hover effect as I wanted as the JLabeldoes not appear to update. I have tried updating the Frame directly by calling frame.update(getGraphics());but that does not appear to work as I think it does.

研究MouseAdapter class应该允许我做我想做的一切,不幸的是我在实现悬停效果时遇到了一些麻烦,因为它JLabel似乎没有更新。我曾尝试通过调用直接更新框架,frame.update(getGraphics());但这似乎并不像我认为的那样工作。

Can I get some advice on how to update the label properly.

我能得到一些关于如何正确更新标签的建议吗?

Note: This is just an example with no effort put in to organize the code efficiently

注意:这只是一个例子,没有努力有效地组织代码

public class Window extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 5259700796854880162L;
    private JTextField textField;
    private JLabel lblNewLabel;
    static Window frame;
    int i = 0;

    public Window() {

        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(null);

        lblNewLabel = new JLabel("New label");
        lblNewLabel.setBackground(Color.LIGHT_GRAY);
        lblNewLabel.setBounds(137, 38, 114, 70);
        panel.add(lblNewLabel);
        lblNewLabel.addMouseListener(new LabelAdapter());

        textField = new JTextField();
        textField.setBounds(122, 119, 86, 20);
        panel.add(textField);
        textField.setColumns(10);

    }

    private class LabelAdapter extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            textField.setText(String.valueOf(i));
            i++;
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            lblNewLabel.setBackground(Color.CYAN);

        }

        @Override
        public void mouseExited(MouseEvent e) {
            lblNewLabel.setBackground(Color.LIGHT_GRAY);
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        frame = new Window();

        frame.setSize(900, 700);
        frame.setVisible(true);
    }
}

回答by mKorbel

  1. Windowis reserver name for awt.Window, change this name to e.g. MyWindow

  2. JPanelhas implemented FlowLayout, you can't to use NullLayoutuse built_in LayoutManager, then to use JFrame.pack()before JFrame.setVisiblefor proper sizing on the screen

  3. JLabelis transparent, change that by using JLabel.setOpaque(true);

  4. refresh of Backgroung Colorfrom Mouse over/hoverisn't possible without JLabel.repaint()as last code line in concrete mouse_event, repaint()missing in JLabel API

  1. Window是 的保留名称awt.Window,将此名称更改为例如MyWindow

  2. JPanel已实现FlowLayout,您不能NullLayout使用内置的 LayoutManager,然后使用JFrame.pack()beforeJFrame.setVisible在屏幕上正确调整大小

  3. JLabel是透明的,通过使用改变它 JLabel.setOpaque(true);

  4. 刷新Backgroung Color来自Mouse over/hover也不是没有可能JLabel.repaint()作为混凝土最后代码行mouse_eventrepaint()缺少JLabel API

回答by MadProgrammer

On top of mKorbel's answer...

在 mKorbel 的回答之上......

I don't know why you're going to so much effort, when you could actually make a button look like a label.

我不知道你为什么要付出这么多努力,实际上你可以让按钮看起来像一个标签。

Button or label?

按钮或标签?

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class NotALabel {

    public static void main(String[] args) {
        new NotALabel();
    }

    public NotALabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                final JButton btn = new JButton("Am I label or a button?");
                btn.setContentAreaFilled(false);
                btn.setBorderPainted(false);
                btn.setFocusPainted(false);
                btn.setOpaque(true);
                btn.getModel().addChangeListener(new ChangeListener() {
                    @Override
                    public void stateChanged(ChangeEvent e) {
                        ButtonModel model = (ButtonModel) e.getSource();
                        if (model.isRollover()) {
                            btn.setBackground(Color.CYAN);
                        } else {
                            btn.setBackground(null);
                        }
                    }
                });

                btn.addActionListener(new ActionListener() {
                    private int count = 0;

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        count++;
                        ((JButton) e.getSource()).setText("I'm a super button!! Or label...");
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(btn);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

You should also consider trying to Setting the look and feelor even possibly Modifying the look and feel

您还应该考虑尝试设置外观甚至可能修改外观

回答by Upendra Siripurapu

You can achieve this using MouseListener. Here is the sample progrma.Have a look.

您可以使用MouseListener来实现这一点。 这是示例程序。看一看。