Search code examples
javaswingjbuttonimageiconjtooltip

Creating a custom JButton which surppress CustomTooltip


What I am trying to do there is, when I will create a CButton instance, it will return me a JButton instance which has a customized tooltip and an image layer.

My application runs perfectly, without any errors, custom button tooltip works corectly, but the image layer does not exist on the button (my question is why?), because the image object parameter is sent to JButton.

import java.awt.Color;
import java.awt.Font;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JToolTip;

public class CButton extends JButton
{
    CButton(String text, String source)
    {
        ImageIcon iconButton = new ImageIcon(source);
        new JButton(text, iconButton)
        {
            public JToolTip createToolTip()
            {
                JToolTip toolTip = super.createToolTip();
                toolTip.setForeground(Color.BLACK);
                toolTip.setBackground(Color.WHITE);
                toolTip.setFont(new Font("Arial", Font.PLAIN, 12));
                return toolTip;
            }
        };
    }
};

Solution

  • To customize the behaviour of a component you should be overriding meethods, not creating a new instance of the class you are extending.

    Something like:

    public class CButton extends JButton
    {
        public CButton(String text, Icon icon)
        {
            super(text, icon);
        }
    
        @Override
        public JToolTip createToolTip()
        {
            JToolTip toolTip = super.createToolTip();
            toolTip.setForeground(Color.BLACK);
            toolTip.setBackground(Color.WHITE);
            toolTip.setFont(new Font("Arial", Font.PLAIN, 12));
            return toolTip;
        }
    };