본문 바로가기
Programming/Processing

[ ProceJava ] 한글 입력 가능 텍스트필드 앱 만들기 - 1

by The Programmer 2025. 8. 17.

1. Introduction

 

이 예제는 프로세싱 고급 예제로 초보자용이 아닙니다. 제가 필요해서 올려둡니다. 이 예제는 Processing + Java 하이브리드(?) 앱 예제입니다. Processing 언어와 Java, Java GUI를 구현하는 Swing 등에 대한 충분한 사전 지식이 필요합니다.

 

이 프로그램은 프로세싱에서 자바 확장 기능을 이용하여 완전하게 한글 입력이 가능한 텍스트필드를 만드는 방법을 보여줍니다. 자바 코드가 대량 함유된(?) 사실상의 Java 앱이더라도 근본적으로는 Processing 프로그램입니다. 프로세싱 명령어들의 추가 확장이 100% 자유롭게 가능합니다.

 

이 예제는 한영 타자 연습 프로그램 제작을 위한 핵심 코어 코드 구현으로 작성되었습니다. 날 밤 새워 약간 피곤하군요. 시원한 아이스크림이 갑자기 생각납니다. ^.^;

 

 

2. Code

 

/* 
Program Name : 프로세싱과 자바 통합 GUI (한글 표시 가능 텍스트필드 테스트 앱)
Version : 1.0.1 beta 99
File Name : Java_TextField_Ex_005_.pde
Date : Aug. 16, 2025.
Licence : MIT, Not for Commercial Use Only.
Copyright : All rights are reserved. (C) James. 2025.
Notes : 기본적인 한영 텍스트 입출력 테스트 완료.
*/


import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.InputStream;
import processing.core.PFont;

PFont      pfont;
Font       awtFont;
JLabel     inputLabel;
JTextField inputField;

// 비즈니스 앱용 컬러 팔레트
final Color FIELD_BG        = Color.WHITE;
final Color FIELD_FG        = new Color(51,  51,  51);
final Color BORDER_COLOR    = new Color(200, 200, 200);
final Color FOCUS_BORDER    = new Color(  0, 120, 215);
final Color LABEL_COLOR     = new Color(80,  80,  80);

void setup() {
  size(600, 400);
  surface.setTitle("Processing + Java : 한국어 입력 가능 텍스트필드 앱 (v1.0.1)");    
// 세련된. ^.^;

  // Processing용 한글 PFont 로드
  try {
    pfont = createFont("D2Coding_.ttf", 16, true);
  } catch (Exception e) {
    println("PFont 로드 실패: " + e.getMessage());
    pfont = createFont("SansSerif", 16, true);
  }
  textFont(pfont);
  textSize(16);

  // Swing용 AWT Font 로드
  try {
    InputStream is = createInput("D2Coding_.ttf");
    if (is == null) throw new Exception("data/D2Coding_.ttf 파일을 확인하세요.");
    awtFont = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(16f);
    is.close();
  } catch (Exception e) {
    println("AWT Font 로드 실패: " + e.getMessage());
    awtFont = new Font("SansSerif", Font.PLAIN, 16);
  }

  // Swing 컴포넌트 추가 (EDT 안전)
  SwingUtilities.invokeLater(() -> {
    Component canvas = (Component) surface.getNative();
    Container parent = canvas.getParent();
    parent.setLayout(null);

    // 레이블: 입력 가이드
    inputLabel = new JLabel(" --> 한글 타자 연습앱 핵심 코드 .. ^.^;");
    inputLabel.setFont(awtFont.deriveFont(Font.PLAIN, 14f));
    inputLabel.setForeground(LABEL_COLOR);
    inputLabel.setBounds(50, 20, 300, 20);

    // 텍스트필드 기본 스타일
    inputField = new JTextField();
    inputField.setFont(awtFont);
    inputField.setOpaque(true);
    inputField.setBackground(FIELD_BG);
    inputField.setForeground(FIELD_FG);
    inputField.setBorder(BorderFactory.createLineBorder(BORDER_COLOR, 1));
    inputField.setBounds(50, 50, 300, 30);
    inputField.setText("Hello, Java! 한국인 James!");

    // 커서 & 깜빡임
    inputField.setCaretColor(FIELD_FG);
    DefaultCaret caret = (DefaultCaret)inputField.getCaret();
    caret.setBlinkRate(500);

    // --- Update 1 시작 : 여기서부터 caret 항상 오른쪽으로 이동 처리 ---
    inputField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
      @Override
      public void insertUpdate(javax.swing.event.DocumentEvent e) {
        // 글자가 확정(insert)된 직후, caret를 맨 끝으로
        SwingUtilities.invokeLater(() ->
          inputField.setCaretPosition(inputField.getDocument().getLength())
        );
      }
      @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { }
      @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { }
    });
    // --- Update 1 끝 : 여기까지 추가 ---

    // 포커스 시 테두리 변경
    inputField.addFocusListener(new FocusAdapter() {
      @Override
      public void focusGained(FocusEvent e) {
        inputField.setBorder(BorderFactory.createLineBorder(FOCUS_BORDER, 2));
      }
      @Override
      public void focusLost(FocusEvent e) {
        inputField.setBorder(BorderFactory.createLineBorder(BORDER_COLOR, 1));
      }
    });

    parent.add(inputLabel);
    parent.add(inputField);

    // Z-순서 보장 & 포커스
    parent.setComponentZOrder(inputField, 0);
    parent.setComponentZOrder(inputLabel, 0);
    parent.revalidate();
    parent.repaint();
    inputField.requestFocusInWindow();
  });
}

void draw() {
  background(243, 242, 241);
  // 전체 배경은 약한 그레이 톤
  fill(45);
  if (inputField != null) {
    text("입력 내용: " + inputField.getText(), 50, 120);
  }
}

 

 

3. Result

 

[ 한영 타자 연습 앱 코어 구현 v1.0.1 b99 ]

 

 

 

4. Notes

Not yet! ^.^;

오늘은 피곤해서 추후.

 

 

 

■ 응용 연습 과제

1) 짧은 글 연습 설계 (기본 폰트 크기를 애들이 쓰기에 적합하게 충분히 크게.) 

2) 긴 글 연습 설계

 

 

5. Files

 

 

Java_TextField_Ex_005_.zip
13.32MB

 

data 폴더 포함.

 

 

6. Ref.

 

1) 황기태, [ 명품 Java Programming, 5E. ] 생능. 2024.

2) Casey Reas, Ben Fry 공저, [ Processing : A Programming Handbook, 2E. ] MIT. 2014.

3) 참고용 코드 : https://grammar.tistory.com/72

 

 

 

Happy Programming!

^.^;