Question

I want to insert document in my TextArea. How can I do it?

I found method setDocument(Document document), but I don't understand, how can I create variable of type Document.

import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;


/**
 * Created by Oleg on 18.04.14.
 */

public class MainForm extends JDialog implements ItemListener, ActionListener {

JPanel panel = new JPanel(/*new FlowLayout(FlowLayout.CENTER,320,80)*/);

CheckboxGroup cbG = new CheckboxGroup();
Checkbox rap, punk, rock, drum;

JLabel label1, label2;

JTextArea textArea;

public MainForm() {
    setSize(640, 860);
    setTitle("Main");

    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    GridLayout experimentLayout = new GridLayout(5,4);

    //setLayout(new BorderLayout(10,10));

    cbG = new CheckboxGroup();

    rap = new Checkbox("Rap", cbG, false);
    punk = new Checkbox("Punk", cbG, false);
    drum = new Checkbox("Drum", cbG, false);
    rock = new Checkbox("Rock", cbG, false);

    label1 = new JLabel("<html><font color='red'>Choose kind of music: </font></html>");
    label1.setFont(new Font("Arial", Font.BOLD, 25));

    label2 = new JLabel("asa");

    panel.setLayout(experimentLayout);
    panel.add(label1);
    panel.add(label2);
    panel.add(rap);
    panel.add(punk);
    panel.add(drum);
    panel.add(rock);
    panel.add(textArea);


    add(panel, BorderLayout.NORTH);

    rap.addItemListener(this);
    punk.addItemListener(this);
    drum.addItemListener(this);
    rock.addItemListener(this);
}

@Override
public void itemStateChanged(ItemEvent e) {
    repaint();


    //if(e.getItem().equals(punk.getLabel()))
        //textArea.setDocument(j);




}

@Override
public void actionPerformed(ActionEvent e) {

}

I want to write a program that displays a Checkbox choice in a field TextArea document with information about the genre. There is an event that is responsible for selecting the flag and in the future it should load document in TextArea), but I can't load document..

Was it helpful?

Solution

One way to do this:

    Document doc = new PlainDocument();
    SimpleAttributeSet set = new SimpleAttributeSet();
    try {
        doc.insertString(0, "your content", set);
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    textArea.setDocument(doc);

camickr mentions you can also use:

    textArea.append("your content") 

For JTextField check this link

How to insert a 'String' in a 'JTextField' to a specific position?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top