Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing the font in a JTextArea for different lines

I would like to append differnt lines of font to the JTextArea, however the last font seems to override the other.

Please help...

import java.awt.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class test extends JFrame {

private static JTextArea referenceTextArea = new JTextArea(10, 10);
private JPanel panel = new JPanel();

public test() {
    this.add(panel);
    panel.add(referenceTextArea);
}

public static void textTest() {
    referenceTextArea.setFont(new Font("Serif", Font.BOLD, 15));
    referenceTextArea.append("line1");
    referenceTextArea.append("\n");

    referenceTextArea.setFont(new Font("Serif", Font.ITALIC, 30));
    referenceTextArea.append("line2");
    referenceTextArea.append("\n");
}

public static void main(String[] args) {
    test frame = new test();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

    textTest();
}
}
like image 946
Ricco Avatar asked Feb 05 '11 07:02

Ricco


People also ask

Can you type in a JTextArea?

The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field.

Is JTextArea editable?

JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text .

How do I create a new line in JTextArea?

When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.

How do I change the text style in Java?

getAvailableFontFamilyNames(); JComboBox comboBox = new JComboBox(fonts);// create a combo box with the array comboBox. setFont(new Font("Times New Roman", Font. PLAIN, 12));// set the font comboBox. setBounds(21, 6, 193, 25);// set size and location add(comboBox);


1 Answers

Try using JEditorPane / JTextPane

http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html

These support HTML formatting. A normal JTextArea's setFont method will just set the font for the entire textarea.

like image 74
Matt Eskridge Avatar answered Sep 21 '22 01:09

Matt Eskridge