Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

java - Delayed text color change in Swing text field

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

BlinkColorTextField

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();
            }
        });
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...