java如何换颜色
修改文本颜色(控制台输出)
在Java控制台中,默认不支持直接修改文本颜色,但可以通过ANSI转义码实现。以下是一个示例代码:
public class ConsoleColor {
// ANSI颜色代码
public static final String RESET = "\u001B[0m";
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String YELLOW = "\u001B[33m";
public static void main(String[] args) {
System.out.println(RED + "红色文本" + RESET);
System.out.println(GREEN + "绿色文本" + RESET);
System.out.println(YELLOW + "黄色文本" + RESET);
}
}
修改Swing组件颜色
对于GUI应用程序,可以使用Swing的setForeground()和setBackground()方法:
import javax.swing.*;
import java.awt.*;
public class SwingColorExample {
public static void main(String[] args) {
JFrame frame = new JFrame("颜色示例");
JLabel label = new JLabel("彩色文本");
// 设置前景色(文本颜色)
label.setForeground(Color.BLUE);
// 设置背景色
label.setBackground(Color.YELLOW);
label.setOpaque(true); // 必须设置为不透明才能显示背景色
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
修改JavaFX组件颜色
在JavaFX中,可以通过CSS样式或直接方法设置颜色:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXColorExample extends Application {
@Override
public void start(Stage primaryStage) {
Label label = new Label("彩色文本");
// 方法1:直接设置样式
label.setStyle("-fx-text-fill: red; -fx-background-color: yellow;");
// 方法2:使用预定义颜色
// label.setTextFill(Color.BLUE);
StackPane root = new StackPane();
root.getChildren().add(label);
Scene scene = new Scene(root, 300, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
修改HTML文本颜色(JEditorPane)
如果需要在Swing中显示带颜色的HTML内容:

import javax.swing.*;
public class HTMLColorExample {
public static void main(String[] args) {
JFrame frame = new JFrame("HTML颜色示例");
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setText("<html><body><font color='red'>红色文本</font><br>"
+ "<font color='blue'>蓝色文本</font></body></html>");
frame.add(editorPane);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}






