自定义文本字段UI外观和;感觉

时间:2013-03-03 13:26:50

标签: java swing user-interface

下面的代码允许更改默认的TextFieldUI,以允许您在JTextField上显示提示。 我遇到的问题是,我正在使用nimbus外观和感觉我的程序,当我更改这个textfieldUI时,一切正常,因为它应该,但文本字段的外观和感觉变为丑陋的看起来。我想,既然我要覆盖默认值,我应该手动设置这段代码的外观,但只是不知道怎么做!

import java.awt.Color;
java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;

public class HintTextFieldUI extends BasicTextFieldUI implements FocusListener {

private String hint;
private boolean hideOnFocus;
private Color color;

public Color getColor() {
    return color;
}

public void setColor(Color color) {
    this.color = color;
    repaint();
}

private void repaint() {
    if(getComponent() != null) {
        getComponent().repaint();           
    }
}

public boolean isHideOnFocus() {
    return hideOnFocus;
}

public void setHideOnFocus(boolean hideOnFocus) {
    this.hideOnFocus = hideOnFocus;
    repaint();
}

public String getHint() {
    return hint;
}

public void setHint(String hint) {
    this.hint = hint;
    repaint();
}
public HintTextFieldUI(String hint) {
    this(hint,false);
}

public HintTextFieldUI(String hint, boolean hideOnFocus) {
    this(hint,hideOnFocus, null);
}

public HintTextFieldUI(String hint, boolean hideOnFocus, Color color) {
    this.hint = hint;
    this.hideOnFocus = hideOnFocus;
    this.color = color;
}

@Override
protected void paintSafely(Graphics g) {
    super.paintSafely(g);
    JTextComponent comp = getComponent();
    comp.setu
    if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
        if(color != null) {
            g.setColor(color);
        } else {
            g.setColor(comp.getForeground().brighter().brighter().brighter());              
        }
        int padding = (comp.getHeight() - comp.getFont().getSize())/2;
        g.drawString(hint, 2, comp.getHeight()-padding-1);          
    }
}

@Override
protected void installListeners() {
    super.installListeners();
    getComponent().addFocusListener(this);
}
@Override
protected void uninstallListeners() {
    super.uninstallListeners();
    getComponent().removeFocusListener(this);
}

public void focusGained(FocusEvent e) {
    // TODO Auto-generated method stub
    if(hideOnFocus) repaint();
}

public void focusLost(FocusEvent e) {
    // TODO Auto-generated method stub
    if(hideOnFocus) repaint();  
}

}

1 个答案:

答案 0 :(得分:1)

我不知道nimbus风格是什么样的,但也许Text Prompt可能适合你。