To set the font and color of JTextArea
we can use the setFont()
and setForeground()
methods of the JTextArea
. To create a font we must define the font name, the font style and its size. For the colors we can uses the constant color values defined by the Color
class.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class TextAreaFontDemo extends JPanel {
public TextAreaFontDemo() {
initializeUI();
}
private static void showFrame() {
JPanel panel = new TextAreaFontDemo();
panel.setOpaque(true);
JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TextAreaFontDemo::showFrame);
}
private void initializeUI() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 200));
JTextArea textArea = new JTextArea(5, 40);
textArea.setLineWrap(true);
textArea.setText("The quick brown fox jumps over the lazy dog.");
// Sets JTextArea font and color.
Font font = new Font("Segoe Script", Font.BOLD, 20);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
JScrollPane scrollPane = new JScrollPane(textArea);
this.add(scrollPane, BorderLayout.CENTER);
}
}
Here is the program screenshot of the code snippet above:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024