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 JTextFieldPlaceholder extends JTextField {
15      
16      /**
17       * Log4j logger sent to view.
18       */
19      private static final Logger LOGGER = LogManager.getRootLogger();
20      
21      /**
22       * Text to display when empty.
23       */
24      private String placeholderText;
25      
26      /**
27       * Create a textfield with hint and default value.
28       * @param placeholder Text displayed when empty
29       * @param value Default value
30       */
31      public JTextFieldPlaceholder(String placeholder, String value) {
32          
33          this(placeholder);
34          this.setText(value);
35      }
36      
37      /**
38       * Create a textfield with hint.
39       * @param placeholder Text displayed when empty
40       */
41      public JTextFieldPlaceholder(String placeholder) {
42          this.placeholderText = placeholder;
43      }
44  
45      @Override
46      public void paint(Graphics g) {
47          
48          try {
49              super.paint(g);
50          } catch (ClassCastException e) {  // Fix #4301, ClassCastException: sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData
51              LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
52          }
53          
54          if (this.getText().isEmpty()) {
55              
56              int h = this.getHeight();
57              var fm = g.getFontMetrics();
58  
59              UiUtil.drawPlaceholder(this, g, this.placeholderText, h / 2 + fm.getAscent() / 2 - 1);
60          }
61      }
62  
63      public void setPlaceholderText(String placeholderText) {
64          this.placeholderText = placeholderText;
65      }
66  }