在TextArea java中插入文档(.doc)

时间:2014-04-18 18:33:31

标签: java swing document

我想在TextArea中插入文档。我该怎么办?

我找到了方法setDocument(文档文档),但我不明白,如何创建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) {

}

我想编写一个程序,在字段TextArea文档中显示一个Checkbox选项,其中包含有关该类型的信息。有一个事件负责选择标志,并且将来它应该在TextArea中加载文档),但是我无法加载文档..

1 个答案:

答案 0 :(得分:0)

一种方法:

    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提到你也可以使用:

    textArea.append("your content") 

JTextField点击此链接

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