JAVA

[JAVA] JTextField 커스텀마이징 2

Coding🌱 2025. 3. 27. 19:52
반응형
SMALL

1. JTextField 입력값 변경하는 방법

방법 1 : JPasswordField 사용

JPasswordField는 비밀번호 입력을 위한 전용 필드이며 setEchoChar("특수기호")을 사용해 입력값을 자동으로 특수기호로 표시합니다. 이 방식은 보안성이 높아 비밀번호 입력에 적합합니다.

 
 
 
JAVA
JPasswordField textField = new JPasswordField(20);
textField.setEchoChar("특수기호");

방법 2 : JTextField + KeyListener 사용

KeyListener를 사용해 실제 입력값은 StringBuilder에 저장하고 필드에는 특수기호만 보이도록 합니다. 이 방법은 JPasswordField보다 커스텀 마이징이 가능하지만 보안성은 상대적으로 낮습니다.

 
 
 
JAVA
JTextField textField = new JTextField(20);
StringBuilder password = new StringBuilder();
textField.addKeyListener(new KeyAdapter() {
	@Override
	public void keyTyped(KeyEvent e) {
		e.consume();
		password.append(e.getKeyChar());
		textField.setText("특수기호".repeat(password.length()));
	}
});

2. JTextField 특정 문자만 입력하도록 제한하는 방법

방법 1 : KeyListener를 활용한 입력 제한

KeyListener를 사용하여 입력되는 문자를 실시간으로 감지하고 제한할 수 있지만 복사/붙여넣기 등의 입력은 제어할 수 없다는 단점이 있습니다.

 
 
 
JAVA
JTextField textField = new JTextField(20);

textField.addKeyListener(new KeyAdapter() {
    private final Pattern pattern = Pattern.compile("정규식");

    @Override
    public void keyTyped(KeyEvent e) {
        if (!pattern.matcher(String.valueOf(e.getKeyChar())).matches()) {
            e.consume();
        }
    }
});

방법 2 : DocumentFilter를 활용한 입력 제한

DocumentFilter를 사용하면 복사/붙여넣기 입력도 제어할 수 있어 KeyListener보다 안정적이며 JTextField의 기본 Document를 PlainDocument로 변경해야 합니다.

 

(1) 익명 클래스로 숫자만 입력 허용

 
 
 
JAVA
JTextField textField = new JTextField(20);

AbstractDocument doc = new PlainDocument();
textField.setDocument(doc); 
doc.setDocumentFilter(new DocumentFilter() {
	@Override
	public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
		if (string.matches("정규식")) {
			super.insertString(fb, offset, string, attr);
		}
	}
	@Override
	public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
		if (text.matches("정규식")) {
			super.replace(fb, offset, length, text, attrs);
		}
	}
});

 

(2) 별도의 DocumentFilter 클래스로 숫자 입력 제한

 

DocumentFilter별도 클래스로 분리하여 재사용할 수 있도록 구현한 방식입니다.

 
 
 
JAVA
JTextField textField = new JTextField(20);
/*
 * AbstractDocument doc = new PlainDocument();
 * textField.setDocument(doc);
 * doc.setDocumentFilter(new NumericDocumentFilter());
 */
((AbstractDocument) textField.getDocument()).setDocumentFilter(new NumericDocumentFilter());

class NumericDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
        if (string.matches("정규식")) {
            super.insertString(fb, offset, string, attr);
        }
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        if (text.matches("정규식")) {
            super.replace(fb, offset, length, text, attrs);
        }
    }
}

3. JTextField 입력 필드에 안내문구(힌트) 추가하기

 
 
 
JAVA
JTextField textField = new JTextField(20);
textField.setText("JTextField with Hint");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusAdapter() {
	@Override
	public void focusGained(FocusEvent e) {
		if (textField.getText().equals("JTextField with Hint")) {
			textField.setText("");
			textField.setForeground(Color.BLACK);
		}
	}
	@Override
	public void focusLost(FocusEvent e) {
		if (textField.getText().isEmpty()) {
			textField.setForeground(Color.GRAY);
			textField.setText("JTextField with Hint");
		}
	}
});

4. JTextField 입력 마스크 적용 하는 방법

입력 마스크는 사용자가 전화번호나 날짜처럼 정해진 형식으로 데이터를 입력하도록 돕는 기능입니다. 이 기능을 사용하면 사용자가 형식에 맞게 자동으로 입력할 수 있어 실수를 줄이고 더 쉽게 데이터를 입력할 수 있습니다.

 

 
 
 
JAVA
JFormattedTextField textField = null;
try {
	MaskFormatter formatter = new MaskFormatter("### - #### - ####");
	textField = new JFormattedTextField(formatter);
	textField.setColumns(20);
} catch (ParseException e1) {
	e1.printStackTrace();
}

 

 

반응형
LIST