swing

swing JTextField hint 표시 소스

선원태 2013. 2. 20. 14:37

요즘 한창 스윙으로 삽질중인데 안드로이드에서 기본적으로 제공하는 기능들을 스윙에서는 제공하질 않는다.


이런것들 떔에 커스텀으로 직접 구현해줘야되는데 JTextField의 hint기능도 마찬가지다.


일단 클래스를 하나 만들어서 다음과 같이 작성한다.


package com.dinnovan.skbopenapi.simulator.common;


import java.awt.Color;

import java.awt.event.FocusEvent;

import java.awt.event.FocusListener;

import java.beans.PropertyChangeEvent;

import java.beans.PropertyChangeListener;


import javax.swing.JTextField;

import javax.swing.event.DocumentEvent;

import javax.swing.event.DocumentListener;


public class TextHint implements FocusListener, DocumentListener, PropertyChangeListener {

private final JTextField textfield;

private boolean isEmpty;

private Color hintColor;

private Color foregroundColor;

private final String hintText;


public TextHint(final JTextField textfield, String hintText) {

super();

this.textfield = textfield;

this.hintText = hintText;

this.hintColor = Color.LIGHT_GRAY;

textfield.addFocusListener(this);

registerListeners();

updateState();

if (!this.textfield.hasFocus()) {

focusLost(null);

}

}


public void delete() {

unregisterListeners();

textfield.removeFocusListener(this);

}


private void registerListeners() {

textfield.getDocument().addDocumentListener(this);

textfield.addPropertyChangeListener("foreground", this);

}


private void unregisterListeners() {

textfield.getDocument().removeDocumentListener(this);

textfield.removePropertyChangeListener("foreground", this);

}


public Color getGhostColor() {

return hintColor;

}


public void setGhostColor(Color hintColor) {

this.hintColor = hintColor;

}


private void updateState() {

isEmpty = textfield.getText().length() == 0;

foregroundColor = textfield.getForeground();

}


@Override

public void focusGained(FocusEvent e) {

if (isEmpty) {

unregisterListeners();

try {

textfield.setText("");

textfield.setForeground(foregroundColor);

} finally {

registerListeners();

}

}


}


@Override

public void focusLost(FocusEvent e) {

if (isEmpty) {

unregisterListeners();

try {

textfield.setText(hintText);

textfield.setForeground(hintColor);

} finally {

registerListeners();

}

}

}


@Override

public void propertyChange(PropertyChangeEvent evt) {

updateState();

}


@Override

public void changedUpdate(DocumentEvent e) {

updateState();

}


@Override

public void insertUpdate(DocumentEvent e) {

updateState();

}


@Override

public void removeUpdate(DocumentEvent e) {

updateState();

}


}


사용은 TextHint hint = new TextHint(JTextField, String); 로 사용하면 된다.