鼠标滑过 JLabel 时不显示文本

Text not displayed when mouse is rolled over JLabel

使用 NetBeans (Java),我在 JLabel 中遇到问题。我已指定一个图像作为该 JLabel 的图标。

问题 - 第一个:

我想在该图标(图像)下方显示一些文本(例如 - 注销)。如何做到这一点?

问题 - 第二个:

我想在鼠标滑过 JLabel 时显示一些文本。我该怎么办?

所以,请大家告诉我如何通过编写代码来完成这些事情。

我建议阅读基本的 Oracle 教程,其中详细描述了如何完成此操作。您可以使用 MouseMotionListener to determine when the mouse is rolled over the JLabel, and you can position the JLabel text underneath the Icon of the JLabel by setting its vertical text position as described in the JLabel Tutorial。这些都应该通过对您的问题进行简单的互联网搜索来找到,您的问题表明在提问之前没有完成(并且应该已经完成​​)

1.

创建一个包含两个 JLabelJPanel。这样就可以控制内部组件的布局了。

我使用 BoxLayout 和参数 BoxLayout.Y_AXIS 来获取图标下方的标签。

2.

使用方法 component.addMouseListener(new MouseAdapter() { ... }); 添加 MouseListener,您需要创建一个 MouseAdapter and implement any methods you need (click here)

这是给你的一个工作示例,伙计...根据需要调整它。

注意:您需要更改 ImageIcon()

file-path
public static void main(String[] args) {

    JFrame frame = new JFrame();
    JPanel container = new JPanel();
    JPanel iconLabelPanel = new JPanel();

    String TEXT_FIELD_TEXT = "Hover over the logout label.";

    JLabel icon = new JLabel(new ImageIcon("C:\Users\Gary\Google Drive\Pictures\puush\ss (2015-02-19 at 06.00.00).png"));
    JLabel label = new JLabel("Logout!");
    JTextField textField = new JTextField(TEXT_FIELD_TEXT);

    //Add a mouse motion listener for the JLabel
    label.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseEntered(MouseEvent e) {
            //Set text of another component
            textField.setText("You're over Logout!");
        }

        @Override
        public void mouseExited(MouseEvent e) {
            //Set text of another component
            textField.setText(TEXT_FIELD_TEXT);
        }
    });


    //Add components and set parameters for iconLabelPanel
    iconLabelPanel.setLayout(new BoxLayout(iconLabelPanel, BoxLayout.PAGE_AXIS));
    iconLabelPanel.add(icon);
    iconLabelPanel.add(label);

    //Add components and set parameters for container
    container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
    container.add(iconLabelPanel);
    container.add(textField);

    //Set parameters for frame
    frame.add(container);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setSize(400, 400);
    frame.setVisible(true);
}