如何将从MySQL获取的activity变量设为红色显示在JTextArea?
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:
StyledDocumentlets 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

