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

标签 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();  
}

}

最佳答案

我不知道灵气风格是什么样的,但也许Text Prompt将为您工作。

关于java - 自定义文本字段 UI 外观和感觉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15186147/

相关文章:

c# - Java GUI 中的 C# gridview 是什么?

java - 在 Swing Java 中创建自定义列表

android - 在 Android 中创建 EditText View 行

iPhone 失去了所有 UI 过渡动画

java - 使用 MongoDb 进行 Elasticsearch

java - 在java中使用lambda获取列表中的值总和

java - Android JNI 调用方法 GetStringUTFLength 崩溃

java - 我应该手动提交这个 Play!交易?

Java:Netbeans 中的 JLayeredPane

java - 如何停止 Java 运行整个代码而不等待用户的 Gui 输入