Delayed text color change in Swing text field

你。 提交于 2019-11-30 09:34:22

问题


Is it possible to change the color of a text in a text field?I am trying to build an interpreter, so I was wondering on how would you change the color of the text in real time. For example the word I enter in the text field is:

printf("hi");

The word printf becomes green after a few seconds.

Is it possible?


回答1:


package test;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class BlinkColorTextField {

    BlinkColorTextField() {
        final JTextField blinkingText = new JTextField("Red & Blue");
        ActionListener blinker = new ActionListener() {
            boolean isRed = true;
            public void actionPerformed(ActionEvent ae) {
                if (isRed) {
                    blinkingText.setForeground(Color.BLUE);
                } else {
                    blinkingText.setForeground(Color.RED);
                }
                isRed = !isRed;
            }
        };
        Timer timer = new Timer(1000, blinker);
        timer.start();
        JOptionPane.showMessageDialog(null, blinkingText);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new BlinkColorTextField();
            }
        });
    }

}



回答2:


Try this:

HighlightPainter greenPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);

//in a thread...    
Highlighter h = tf.getHighlighter();
h.addHighlight(offset, offset+length, greenPainter); 



回答3:


You have to use JEditorPane / JTextPane instead of JTextField and also you can draw the text/string by overriding the paintComponent method.



来源:https://stackoverflow.com/questions/9803658/delayed-text-color-change-in-swing-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!