You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将从MySQL获取的activity变量设为红色显示在JTextArea?

Can I Display the "activity" String in Red?

Absolutely! You can make the activity value appear in red, but JTextArea doesn’t support colored or styled text out of the box. To achieve this, you’ll need to switch to a JTextPane (a Swing component built for rich text formatting) and use a StyledDocument to apply color to specific parts of your content.

Step-by-Step Implementation

1. Replace JTextArea with JTextPane

First, swap your existing JTextArea (named jTextAreaActivity) with a JTextPane in your UI. If you’re using a GUI builder (like NetBeans or IntelliJ), just drag-and-drop a JTextPane instead. If creating components programmatically, replace:

JTextArea jTextAreaActivity = new JTextArea();

with:

JTextPane jTextPaneActivity = new JTextPane();

2. Fix Your Database Query (Critical Security Improvement)

Your original query uses string concatenation to insert the n value, which is vulnerable to SQL injection. Let’s rewrite it to use parameterized queries instead—this is a best practice you should always follow.

3. Apply Red Color to the Activity String

Use StyledDocument to define a red style, then insert the activity text with that style, followed by the rest of the content in the default style.

Revised Code

import java.awt.Color;
import javax.swing.JOptionPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.sql.*;

public void Select() {
    int n = 1;
    
    // Reuse the connection outside the loop for better performance
    try (Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", 
            "root", "")) {
        
        String validate = "SELECT * FROM history WHERE UserActivityID = ?";
        try (PreparedStatement smtm = con.prepareStatement(validate)) {
            
            for (int i = 0; i < numberRow; i++) {
                smtm.setInt(1, n); // Safely set the parameter to avoid SQL injection
                try (ResultSet rs = smtm.executeQuery()) {
                    if (rs.next()) {
                        String time = rs.getString("UserTimeActivity");
                        String activity = rs.getString("UserActivity");
                        
                        // Get the document from the JTextPane
                        StyledDocument doc = jTextPaneActivity.getStyledDocument();
                        
                        // Create a red style
                        Style redStyle = jTextPaneActivity.addStyle("RedStyle", null);
                        StyleConstants.setForeground(redStyle, Color.RED);
                        
                        // Insert the red activity text
                        doc.insertString(doc.getLength(), activity, redStyle);
                        // Insert the rest of the text with default style
                        doc.insertString(doc.getLength(), " - " + time + "\n", null);
                        
                        n++;
                    }
                }
            }
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this, "Database error: " + ex.getMessage());
    } catch (HeadlessException ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage());
    }
}

Key Notes

  • Resource Management: We use try-with-resources (try (Connection con = ...)) to automatically close database resources (connections, statements, result sets) when they’re no longer needed—this prevents resource leaks.
  • SQL Injection Prevention: Parameterized queries (? placeholder + setInt) eliminate the risk of SQL injection attacks.
  • Styled Text: StyledDocument lets you apply different styles (color, font size, bold, etc.) to specific parts of your text, which is exactly what you need here.

If you absolutely must use JTextArea (not recommended for styled text), you’d have to implement a custom component or use HTML rendering—but JTextPane is the standard, straightforward solution for this use case.

内容的提问来源于stack exchange,提问作者Ariff Naj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:33:43