TextField: support leading and trailing icons (issue #368)

This commit is contained in:
Karl Tauber
2021-09-02 17:45:33 +02:00
parent 51d7bc2c37
commit dc33c26960
21 changed files with 571 additions and 73 deletions

View File

@@ -745,6 +745,26 @@ public interface FlatClientProperties
*/
String TEXT_FIELD_PADDING = "JTextField.padding";
/**
* Specifies an icon that will be placed at the leading edge of the text field.
* <p>
* <strong>Component</strong> {@link javax.swing.JTextField} (and subclasses)<br>
* <strong>Value type</strong> {@link javax.swing.Icon}
*
* @since 2
*/
String TEXT_FIELD_LEADING_ICON = "JTextField.leadingIcon";
/**
* Specifies an icon that will be placed at the trailing edge of the text field.
* <p>
* <strong>Component</strong> {@link javax.swing.JTextField} (and subclasses)<br>
* <strong>Value type</strong> {@link javax.swing.Icon}
*
* @since 2
*/
String TEXT_FIELD_TRAILING_ICON = "JTextField.trailingIcon";
//---- JToggleButton ------------------------------------------------------
/**
@@ -813,8 +833,7 @@ public interface FlatClientProperties
* If the client property is not set, or not a {@link Boolean}, defaultValue is returned.
*/
static Boolean clientPropertyBooleanStrict( JComponent c, String key, Boolean defaultValue ) {
Object value = c.getClientProperty( key );
return (value instanceof Boolean) ? (Boolean) value : defaultValue;
return clientProperty( c, key, defaultValue, Boolean.class );
}
/**
@@ -831,7 +850,18 @@ public interface FlatClientProperties
* If the client property is not set, or not a color, defaultValue is returned.
*/
static Color clientPropertyColor( JComponent c, String key, Color defaultValue ) {
return clientProperty( c, key, defaultValue, Color.class );
}
/**
* Returns the value of the specified client property if it is an instance of
* the specified type. Otherwise, defaultValue is returned.
*
* @since 2
*/
@SuppressWarnings( "unchecked" )
static <T> T clientProperty( JComponent c, String key, T defaultValue, Class<T> type ) {
Object value = c.getClientProperty( key );
return (value instanceof Color) ? (Color) value : defaultValue;
return type.isInstance( value ) ? (T) value : defaultValue;
}
}

View File

@@ -18,7 +18,6 @@ package com.formdev.flatlaf.ui;
import static com.formdev.flatlaf.FlatClientProperties.*;
import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;
@@ -68,11 +67,12 @@ public class FlatCaret
protected void adjustVisibility( Rectangle nloc ) {
JTextComponent c = getComponent();
if( c != null && c.getUI() instanceof FlatTextFieldUI ) {
Insets padding = ((FlatTextFieldUI)c.getUI()).getPadding();
if( padding != null ) {
nloc.x -= padding.left;
nloc.y -= padding.top;
}
// need to fix x location because JTextField.scrollRectToVisible() uses insets.left
// (as BasicTextUI.getVisibleEditorRect() does),
// but FlatTextFieldUI.getVisibleEditorRect() may add some padding
Rectangle r = ((FlatTextFieldUI)c.getUI()).getVisibleEditorRect();
if( r != null )
nloc.x -= r.x - c.getInsets().left;
}
super.adjustVisibility( nloc );
}

View File

@@ -43,6 +43,7 @@ import javax.swing.plaf.ComponentUI;
* @uiDefault Component.isIntelliJTheme boolean
* @uiDefault FormattedTextField.placeholderForeground Color
* @uiDefault FormattedTextField.focusedBackground Color optional
* @uiDefault FormattedTextField.iconTextGap int optional, default is 4
* @uiDefault TextComponent.selectAllOnFocusPolicy String never, once (default) or always
* @uiDefault TextComponent.selectAllOnMouseClick boolean
*

View File

@@ -17,8 +17,7 @@
package com.formdev.flatlaf.ui;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Shape;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
@@ -36,6 +35,7 @@ import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.PasswordView;
import javax.swing.text.View;
import com.formdev.flatlaf.util.UIScale;
/**
* Provides the Flat LaF UI delegate for {@link javax.swing.JPasswordField}.
@@ -61,6 +61,7 @@ import javax.swing.text.View;
* @uiDefault Component.isIntelliJTheme boolean
* @uiDefault PasswordField.placeholderForeground Color
* @uiDefault PasswordField.focusedBackground Color optional
* @uiDefault PasswordField.iconTextGap int optional, default is 4
* @uiDefault TextComponent.selectAllOnFocusPolicy String never, once (default) or always
* @uiDefault TextComponent.selectAllOnMouseClick boolean
*
@@ -160,29 +161,38 @@ public class FlatPasswordFieldUI
return new PasswordView( elem );
}
/** @since 2 */
@Override
protected void paintSafely( Graphics g ) {
// safe and restore clipping area because super.paintSafely() modifies it
// and the caps lock icon would be truncated
Shape oldClip = g.getClip();
super.paintSafely( g );
g.setClip( oldClip );
protected void paintIcons( Graphics g, Rectangle r ) {
super.paintIcons( g, r );
paintCapsLock( g );
if( isCapsLockVisible() )
paintCapsLock( g, r );
}
protected void paintCapsLock( Graphics g ) {
if( !isCapsLockVisible() )
return;
/** @since 2 */
protected void paintCapsLock( Graphics g, Rectangle r ) {
JTextComponent c = getComponent();
int y = (c.getHeight() - capsLockIcon.getIconHeight()) / 2;
int x = c.getComponentOrientation().isLeftToRight()
? c.getWidth() - capsLockIcon.getIconWidth() - y
: y;
? r.x + r.width - capsLockIcon.getIconWidth()
: r.x;
int y = r.y + Math.round( (r.height - capsLockIcon.getIconHeight()) / 2f );
capsLockIcon.paintIcon( c, g, x, y );
}
/** @since 2 */
@Override
protected boolean hasTrailingIcon() {
return super.hasTrailingIcon() || isCapsLockVisible();
}
/** @since 2 */
@Override
protected int getTrailingIconWidth() {
return super.getTrailingIconWidth()
+ (isCapsLockVisible() ? capsLockIcon.getIconWidth() + UIScale.scale( iconTextGap ) : 0);
}
/**
* @since 1.4
*/
@@ -194,18 +204,4 @@ public class FlatPasswordFieldUI
return FlatUIUtils.isPermanentFocusOwner( c ) &&
Toolkit.getDefaultToolkit().getLockingKeyState( KeyEvent.VK_CAPS_LOCK );
}
/**
* @since 1.4
*/
@Override
protected Insets getPadding() {
Insets padding = super.getPadding();
if( !isCapsLockVisible() )
return padding;
boolean ltr = getComponent().getComponentOrientation().isLeftToRight();
int iconWidth = capsLockIcon.getIconWidth();
return FlatUIUtils.addInsets( padding, new Insets( 0, ltr ? 0 : iconWidth, 0, ltr ? iconWidth : 0 ) );
}
}

View File

@@ -16,6 +16,7 @@
package com.formdev.flatlaf.ui;
import static com.formdev.flatlaf.FlatClientProperties.*;
import static com.formdev.flatlaf.util.UIScale.scale;
import java.awt.Color;
import java.awt.Container;
@@ -28,6 +29,7 @@ import java.awt.Rectangle;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.util.Objects;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JSpinner;
@@ -39,10 +41,8 @@ import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.Caret;
import javax.swing.text.JTextComponent;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.util.HiDPIUtils;
import com.formdev.flatlaf.util.JavaCompatibility;
import com.formdev.flatlaf.util.UIScale;
/**
* Provides the Flat LaF UI delegate for {@link javax.swing.JTextField}.
@@ -68,6 +68,7 @@ import com.formdev.flatlaf.util.UIScale;
* @uiDefault Component.isIntelliJTheme boolean
* @uiDefault TextField.placeholderForeground Color
* @uiDefault TextField.focusedBackground Color optional
* @uiDefault TextField.iconTextGap int optional, default is 4
* @uiDefault TextComponent.selectAllOnFocusPolicy String never, once (default) or always
* @uiDefault TextComponent.selectAllOnMouseClick boolean
*
@@ -80,6 +81,10 @@ public class FlatTextFieldUI
protected boolean isIntelliJTheme;
protected Color placeholderForeground;
protected Color focusedBackground;
protected int iconTextGap;
protected Icon leadingIcon;
protected Icon trailingIcon;
private Insets defaultMargin;
@@ -89,6 +94,22 @@ public class FlatTextFieldUI
return new FlatTextFieldUI();
}
@Override
public void installUI( JComponent c ) {
super.installUI( c );
leadingIcon = clientProperty( c, TEXT_FIELD_LEADING_ICON, null, Icon.class );
trailingIcon = clientProperty( c, TEXT_FIELD_TRAILING_ICON, null, Icon.class );
}
@Override
public void uninstallUI( JComponent c ) {
super.uninstallUI( c );
leadingIcon = null;
trailingIcon = null;
}
@Override
protected void installDefaults() {
super.installDefaults();
@@ -98,6 +119,7 @@ public class FlatTextFieldUI
isIntelliJTheme = UIManager.getBoolean( "Component.isIntelliJTheme" );
placeholderForeground = UIManager.getColor( prefix + ".placeholderForeground" );
focusedBackground = UIManager.getColor( prefix + ".focusedBackground" );
iconTextGap = FlatUIUtils.getUIInt( prefix + ".iconTextGap", 4 );
defaultMargin = UIManager.getInsets( prefix + ".margin" );
@@ -142,20 +164,28 @@ public class FlatTextFieldUI
@Override
protected void propertyChange( PropertyChangeEvent e ) {
super.propertyChange( e );
propertyChange( getComponent(), e );
}
static void propertyChange( JTextComponent c, PropertyChangeEvent e ) {
JTextComponent c = getComponent();
switch( e.getPropertyName() ) {
case FlatClientProperties.PLACEHOLDER_TEXT:
case FlatClientProperties.COMPONENT_ROUND_RECT:
case FlatClientProperties.TEXT_FIELD_PADDING:
case PLACEHOLDER_TEXT:
case COMPONENT_ROUND_RECT:
case TEXT_FIELD_PADDING:
c.repaint();
break;
case FlatClientProperties.MINIMUM_WIDTH:
case MINIMUM_WIDTH:
c.revalidate();
break;
case TEXT_FIELD_LEADING_ICON:
leadingIcon = (e.getNewValue() instanceof Icon) ? (Icon) e.getNewValue() : null;
c.repaint();
break;
case TEXT_FIELD_TRAILING_ICON:
trailingIcon = (e.getNewValue() instanceof Icon) ? (Icon) e.getNewValue() : null;
c.repaint();
break;
}
}
@@ -164,6 +194,15 @@ public class FlatTextFieldUI
paintBackground( g, getComponent(), isIntelliJTheme, focusedBackground );
paintPlaceholder( g );
if( hasLeadingIcon() || hasTrailingIcon() )
paintIcons( g, new Rectangle( getIconsRect() ) );
/*debug
Rectangle r = getVisibleEditorRect();
g.setColor( Color.red );
g.drawRect( r.x, r.y, r.width - 1, r.height - 1 );
debug*/
super.paintSafely( HiDPIUtils.createGraphicsTextYCorrection( (Graphics2D) g ) );
}
@@ -230,15 +269,15 @@ public class FlatTextFieldUI
JComponent jc = (parent instanceof JComboBox) ? (JComboBox<?>) parent : c;
// get placeholder text
Object placeholder = jc.getClientProperty( FlatClientProperties.PLACEHOLDER_TEXT );
if( !(placeholder instanceof String) )
String placeholder = clientProperty( jc, PLACEHOLDER_TEXT, null, String.class );
if( placeholder == null )
return;
// compute placeholder location
Rectangle r = getVisibleEditorRect();
FontMetrics fm = c.getFontMetrics( c.getFont() );
String clippedPlaceholder = JavaCompatibility.getClippedString( c, fm, (String) placeholder, r.width );
int x = r.x + (c.getComponentOrientation().isLeftToRight() ? 0 : r.width - fm.stringWidth( clippedPlaceholder ));
String clippedPlaceholder = JavaCompatibility.getClippedString( c, fm, placeholder, r.width );
int x = r.x + (isLeftToRight() ? 0 : r.width - fm.stringWidth( clippedPlaceholder ));
int y = r.y + fm.getAscent() + ((r.height - fm.getHeight()) / 2);
// paint placeholder
@@ -246,6 +285,42 @@ public class FlatTextFieldUI
FlatUIUtils.drawString( c, g, clippedPlaceholder, x, y );
}
/**
* Paints the leading and trailing icons in the given rectangle.
* The rectangle is updated by this method so that subclasses can use it
* without painting over leading or trailing icons.
*
* @since 2
*/
protected void paintIcons( Graphics g, Rectangle r ) {
boolean ltr = isLeftToRight();
Icon leftIcon = ltr ? leadingIcon : trailingIcon;
Icon rightIcon = ltr ? trailingIcon : leadingIcon;
// paint left icon
if( leftIcon != null ) {
int x = r.x;
int y = r.y + Math.round( (r.height - leftIcon.getIconHeight()) / 2f );
leftIcon.paintIcon( getComponent(), g, x, y );
// update rectangle so that subclasses can use it
int w = leftIcon.getIconWidth() + scale( iconTextGap );
r.x += w;
r.width -= w;
}
// paint right icon
if( rightIcon != null ) {
int iconWidth = rightIcon.getIconWidth();
int x = r.x + r.width - iconWidth;
int y = r.y + Math.round( (r.height - rightIcon.getIconHeight()) / 2f );
rightIcon.paintIcon( getComponent(), g, x, y );
// update rectangle so that subclasses can use it
r.width -= iconWidth + scale( iconTextGap );
}
}
@Override
public Dimension getPreferredSize( JComponent c ) {
return applyMinimumWidth( c, super.getPreferredSize( c ), minimumWidth );
@@ -283,27 +358,104 @@ public class FlatTextFieldUI
return margin instanceof UIResource && Objects.equals( margin, defaultMargin );
}
/**
* Returns the rectangle used for the root view of the text.
* This method is used to place the text.
*/
@Override
protected Rectangle getVisibleEditorRect() {
Rectangle r = getIconsRect();
if( r == null )
return null;
// remove space needed for leading and trailing icons
int leading = getLeadingIconWidth();
int trailing = getTrailingIconWidth();
if( leading != 0 || trailing != 0 ) {
boolean ltr = isLeftToRight();
int left = ltr ? leading : trailing;
int right = ltr ? trailing : leading;
r.x += left;
r.width -= left + right;
}
// remove padding
Insets padding = getPadding();
if( padding != null )
r = FlatUIUtils.subtractInsets( r, padding );
// make sure that width and height are not negative
r.width = Math.max( r.width, 0 );
r.height = Math.max( r.height, 0 );
return r;
}
/**
* Returns the rectangle used to paint leading and trailing icons.
* It invokes {@code super.getVisibleEditorRect()} and reduces left and/or
* right margin if the text field has leading or trailing icons.
*
* @since 2
*/
protected Rectangle getIconsRect() {
Rectangle r = super.getVisibleEditorRect();
if( r != null ) {
// remove padding
Insets padding = getPadding();
if( padding != null ) {
r = FlatUIUtils.subtractInsets( r, padding );
r.width = Math.max( r.width, 0 );
r.height = Math.max( r.height, 0 );
if( r == null )
return null;
// if a leading/trailing icon is shown, then the left/right margin is reduced
// to the top margin, which places the icon nicely centered on left/right side
boolean ltr = isLeftToRight();
if( ltr ? hasLeadingIcon() : hasTrailingIcon() ) {
// reduce left margin
Insets margin = getComponent().getMargin();
int newLeftMargin = Math.min( margin.left, margin.top );
if( newLeftMargin < margin.left ) {
int diff = scale( margin.left - newLeftMargin );
r.x -= diff;
r.width += diff;
}
}
if( ltr ? hasTrailingIcon() : hasLeadingIcon() ) {
// reduce right margin
Insets margin = getComponent().getMargin();
int newRightMargin = Math.min( margin.right, margin.top );
if( newRightMargin < margin.left )
r.width += scale( margin.right - newRightMargin );
}
return r;
}
/** @since 2 */
protected boolean hasLeadingIcon() {
return leadingIcon != null;
}
/** @since 2 */
protected boolean hasTrailingIcon() {
return trailingIcon != null;
}
/** @since 2 */
protected int getLeadingIconWidth() {
return (leadingIcon != null) ? leadingIcon.getIconWidth() + scale( iconTextGap ) : 0;
}
/** @since 2 */
protected int getTrailingIconWidth() {
return (trailingIcon != null) ? trailingIcon.getIconWidth() + scale( iconTextGap ) : 0;
}
boolean isLeftToRight() {
return getComponent().getComponentOrientation().isLeftToRight();
}
/**
* @since 1.4
*/
protected Insets getPadding() {
Object padding = getComponent().getClientProperty( FlatClientProperties.TEXT_FIELD_PADDING );
return (padding instanceof Insets) ? UIScale.scale( (Insets) padding ) : null;
return scale( clientProperty( getComponent(), TEXT_FIELD_PADDING, null, Insets.class ) );
}
/**

View File

@@ -273,6 +273,7 @@ FormattedTextField.border = com.formdev.flatlaf.ui.FlatTextBorder
FormattedTextField.margin = @textComponentMargin
FormattedTextField.background = @textComponentBackground
FormattedTextField.placeholderForeground = @disabledText
FormattedTextField.iconTextGap = 4
#---- HelpButton ----
@@ -413,6 +414,7 @@ PasswordField.border = com.formdev.flatlaf.ui.FlatTextBorder
PasswordField.margin = @textComponentMargin
PasswordField.background = @textComponentBackground
PasswordField.placeholderForeground = @disabledText
PasswordField.iconTextGap = 4
PasswordField.echoChar = \u2022
PasswordField.showCapsLock = true
PasswordField.capsLockIcon = com.formdev.flatlaf.icons.FlatCapsLockIcon
@@ -680,6 +682,7 @@ TextField.border = com.formdev.flatlaf.ui.FlatTextBorder
TextField.margin = @textComponentMargin
TextField.background = @textComponentBackground
TextField.placeholderForeground = @disabledText
TextField.iconTextGap = 4
#---- TextPane ----