Change text and background color ToolTip

4

How can I change the background color and text of a ToolTip? I already did a search and found here a code snippet but I can not change it. The colors always remain the standard NetBeans. Any suggestions?

I put the following code in the constructor of my class:

     UIManager.put("ToolTip.foreground", Color.BLACK);
     UIManager.put("ToolTip.background", Color.GREEN);
     ToolTipManager.sharedInstance().setInitialDelay(0);
     ToolTipManager.sharedInstance().setDismissDelay(1500);
     jFormattedNIPC.setToolTipText("teste");

Update:

Use HTML in the field properties in the toolTipText section. The color managed to change well, but the background looks like this:

The background color does not fill the 'balloon' completely. Used: <html><p style='background-color:blue; color:white;'>teste</p></html>

    
asked by anonymous 14.11.2014 / 10:48

1 answer

6

Solution 1

Some elements of the swing accept HTML in the text. For example in label you can put something like this in the text: "<html>Palavra em <strong>negrito</strong>.</html>" .

In your case you can do this:

"<html><body style=\"background-color:#d8d8ff;\"><center><br>TESTETETESTE</center></body></ht‌​ml>";

However, as pointed out by the author of the question, this solution does not solve the problem perfectly. It does not leave the background completely filled with color.

Solution 2

You can create a custom ToolTip for the component:

class MyCustomToolTip extends JToolTip {
    public MyCustomToolTip(JComponent component) {
       super();
       setComponent(component);
       setBackground(Color.black);
       setForeground(Color.red);
    }
}

So when you start a component, in this example a jTextField , do so:

jTextField1 = new JTextField("teste"){
    @Override
    public JToolTip createToolTip() {
        return (new MyCustomToolTip(this));
    }
};

Note: if you use NetBeans you can change the tooltip of a component as follows:

  • Put class MyCustomToolTip after method initComponents() ;
  • Right click on the component;
  • Go to Properties;
  • Click the Code tab;
  • In the Custom Creation Code property, click the ... and enter the creation code (in this case a JTextField ):

    new JTextField("teste"){ // Pode ser new JLabel, depende do tipo do componente
        @Override
        public JToolTip createToolTip() {
            return (new MyCustomToolTip(this));
        }
    };
    
  • Ok.

  • 14.11.2014 / 11:16