简体   繁体   中英

Jbutton setTooltip() as ImageIcon?

I've looked around and viewed various threads on here. the one I found closest to what I'm attempting to do is this one:

Hovering over JButtons and displaying a message

Basically I'm trying to replace button.setToolTipText(""); with an ImageIcon. I'm using this as a preview of the next page you're about to visit inside the JFrame, to give to user an Idea or quick overview of the next page. (I have figured out the imaging, just not the ToolTip).

Here is what I tried using based on what I've seen in the various thread, but obviously it didn't work, hence I'm asking this question.

Code I used: Log.setToolTip(new ImageIcon(getIconLog));

You can use MouseListener and JLabel act as a tooltip. Like this...

public static void main(String[] args){
     final JFrame f = new JFrame();
     f.setSize(500, 400);
     f.setVisible(true);
     f.setLayout(null);
     f.setDefaultCloseOperation(3);

     final JButton b = new JButton("ToolTip");
     b.setBounds(100, 100, 70, 70);
     f.add(b);

     final JLabel toolTip = new JLabel();
     b.addMouseListener(new MouseListener() {

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {
            f.remove(toolTip);
            f.repaint();
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            try {
                toolTip.setIcon(new ImageIcon(ImageIO.read(new File("your image"))));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            toolTip.setBounds(b.getLocation().x+b.getWidth(), b.getLocation().y-b.getHeight(), 100, 50);
            f.add(toolTip);
            f.repaint();
        }

        @Override
        public void mouseClicked(MouseEvent e) {

        }
    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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