使用NetBeans(Java),我在JLabel中遇到问题。我已将图像分配为该JLabel的图标。

问题-第一:

我想在该图标(图片)下方显示一些文本(例如,注销)。这该怎么做?

问题-第二:

当鼠标悬停在该JLabel上时,我想显示一些文本。我该怎么办?

因此,请大家通过编写代码告诉我如何进行这些操作。

最佳答案

1。

创建一个包含两个JPanelJLabel。这样,您可以控制内部组件的布局。

我将BoxLayout与参数BoxLayout.Y_AXIS一起使用,以获取图标下方的标签。

2。

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

这是为您的伙伴提供的一个有效示例。

注意:您需要更改file-pathImageIcon()

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);
}

关于java - 鼠标滑过JLabel时不显示文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29778672/

10-12 23:55