View Javadoc
1   package com.jsql.view.swing.text;
2   
3   import com.jsql.util.LogLevelUtil;
4   import com.jsql.view.swing.util.UiUtil;
5   import org.apache.logging.log4j.LogManager;
6   import org.apache.logging.log4j.Logger;
7   
8   import javax.swing.*;
9   import java.awt.*;
10  
11  /**
12   * Textfield with information text displayed when empty.
13   */
14  public class JPasswordFieldPlaceholder extends JPasswordField implements JPlaceholder {
15  
16      private static final Logger LOGGER = LogManager.getRootLogger();
17  
18      /**
19       * Text to display when empty.
20       */
21      private String placeholderText;
22  
23      /**
24       * Create a textfield with hint.
25       * @param placeholder Text displayed when empty
26       */
27      public JPasswordFieldPlaceholder(String placeholder) {
28          this.placeholderText = placeholder;
29      }
30  
31      @Override
32      public void paint(Graphics g) {
33          try {
34              super.paint(g);
35          } catch (ClassCastException e) {  // Fix #4301, ClassCastException: sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData
36              LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
37          }
38          if (new String(this.getPassword()).isEmpty()) {
39              int h = this.getHeight();
40              var fm = g.getFontMetrics();
41              UiUtil.drawPlaceholder(this, g, this.placeholderText, 0, h / 2 + fm.getAscent() / 2 - 1);
42          }
43      }
44  
45      @Override
46      public void setPlaceholderText(String placeholderText) {
47          this.placeholderText = placeholderText;
48      }
49  }