view src/luan/modules/swing/TextFieldLuan.java @ 1914:d5776185f9d7

config
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 17 Apr 2025 18:36:27 -0600
parents 474f7ab2d1c2
children
line wrap: on
line source

package luan.modules.swing;

import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import goodjava.logging.Logger;
import goodjava.logging.LoggerFactory;


public class TextFieldLuan extends JTextField {
	private static final Logger logger = LoggerFactory.getLogger(TextFieldLuan.class);

	private boolean showWhitespace = false;

	public boolean isWhitespaceVisible() {
		return showWhitespace;
	}

	public void setWhitespaceVisible(boolean showWhitespace) {
		this.showWhitespace = showWhitespace;
		repaint();
	}

	@Override protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if( !showWhitespace )
			return;
		g.setColor(Color.LIGHT_GRAY);
		String text = getText();
		int ascent = g.getFontMetrics().getAscent();
		Rectangle visible = getVisibleRect();
		for( int pos=0; pos<text.length(); pos++ ) {
			char ch = text.charAt(pos);
			String symbol;
			switch(ch) {
				case ' ': symbol = "·"; break;
				case '\t': symbol = "→"; break;
				case '\n': symbol = "¶"; break;
				default: continue;
			}
			Rectangle r;
			try {
				r = modelToView(pos);
			} catch(BadLocationException e) {
				throw new RuntimeException(e);
			}
			if( visible.contains(r)	)
				g.drawString( symbol, r.x, r.y + ascent );
		}
	}

	private UndoManagerLuan getUndoManagerLuan() {
		return (UndoManagerLuan)getDocument().getProperty("undo");
	}

	@Override public void paste() {
		UndoManagerLuan undo = getUndoManagerLuan();
		undo.beginTransaction();
		try {
			super.paste();
		} finally {
			undo.endTransaction();
		}
	}
}