简体   繁体   English

Java Swing TextArea:如何在输出 TextArea 中同时打印音译文本?

[英]Java Swing TextArea: How to simultaneously print Transliterated text/s in an Output TextArea?

I am trying to write a text editor.我正在尝试编写一个文本编辑器。 I want two TextAreas: 1st one for typing/editing in unicode script and 2nd one for simultaneously printing output of the unicode script input in corresponding Roman Script (ASCII) set by myself on the basis of a transliteration scheme.我想要两个 TextAreas:第一个用于在 unicode 脚本中输入/编辑,第二个用于同时打印以我自己根据音译方案设置的相应罗马脚本 (ASCII) 中输入的 unicode 脚本的输出。 I am not able to update and simultaneously print the input text in output textarea while I call the transliteration method.我无法在调用音译方法时更新和同时打印输出文本区域中的输入文本。 I can sense a little bit that there is something wrong while I set the output textArea to print simultaneously but I am unable to find out what exactly is that.当我将输出 textArea 设置为同时打印时,我可以感觉到有点问题,但我无法找出到底是什么。

The Editor class------->编辑器类------->



import java.awt.*;
import java.beans.PropertyChangeSupport;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class editor extends JPanel {
    private static final int ROWS = 10;
    private static final int COLS = 50;
    private static final String[] BUTTON_NAMES = {"विविधाः", "द्वाराणि", "Setting", "Parse", "Compile"};
    private static final int GAP = 3;
    private JTextArea inputTextArea = new JTextArea(ROWS, COLS);
    private JTextArea outputTextArea = new JTextArea(ROWS, COLS);
    private JTextArea TA = new JTextArea(ROWS, COLS);

//calling the transliteration method
    transliterator tr = new transliterator();
    Document asciiDocument=tr.DevanagariTransliteration(inputTextArea.getDocument());

    public editor() throws BadLocationException {
        JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
        for (String btnName : BUTTON_NAMES) {
            buttonPanel.add(new JButton(btnName));
        }

        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        add(buttonPanel);

        add(putInTitledScrollPane(inputTextArea, "देवनागरी <<<<<<>>>>>> Devanagari"));

        inputTextArea.setFocusable(true);
        outputTextArea.setFocusable(false);
        outputTextArea.setEditable(false);

        //String inputCheck = inputTextArea.getText();
        //inputTextArea.setText("x");
        //if (inputTextArea.getText().length()>0) {


       outputTextArea.setDocument(asciiDocument);//printing input in 2nd textarea
        // outputTextArea.setDocument(inputTextArea.getDocument());//printing input in 2nd textarea


        add(putInTitledScrollPane(outputTextArea, "IndicASCII"));

    }

    private JPanel putInTitledScrollPane(JComponent component,
                                         String title) {
        JPanel wrapperPanel = new JPanel(new BorderLayout());
        wrapperPanel.setBorder(BorderFactory.createTitledBorder(title));
        wrapperPanel.add(new JScrollPane(component));
        return wrapperPanel;
    }

    private static void createAndShowGui() throws BadLocationException {
        editor mainPanel = new editor();

        JFrame frame = new JFrame("Unicode Editor");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        ImageIcon imgicon = new ImageIcon("MyIcon.jpg");
        frame.setIconImage(imgicon.getImage());
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    createAndShowGui();
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

And transliteration class method:和音译类方法:


import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class transliterator {
    //method that returns a Document type
    // the method - importing devanagari text through the type 'Document' from input textArea by call
    public Document DevanagariTransliteration(Document devanagariTextDocument) throws BadLocationException {
        //extracting the devanagari text from the imported Document type
        String asciiText = devanagariTextDocument.getText(0, devanagariTextDocument.getLength());
        //devanagari unicode a replaced by ascii a
        String transliteratedText = asciiText.replace('\u0905', 'a');

        JTextArea jt = new JTextArea();
        //inserting the TRANSLITERATED text to a textArea to extract as a Document again
        jt.setText(transliteratedText);
        //extracting and creating as a document
        Document ASCIITextDocument = jt.getDocument();
        //returning the document
        return ASCIITextDocument;
    }
}

When I used the setDocument() method I cannot handle the text input当我使用 setDocument() 方法时,我无法处理文本输入

All the setDocument() method does is share the Document between multiple components. setDocument()方法所做的就是在多个组件之间共享文档。 So whatever you type will be displayed in both components.因此,您键入的任何内容都将显示在两个组件中。

Instead you would use a DocumentListener .相反,您将使用DocumentListener The listener will generate an event whenever text is added or removed from the Document.每当在文档中添加或删除文本时,侦听器都会生成一个事件。 Then you will need to read the text from the Document and do your translation and update the second text area.然后您需要阅读文档中的文本并进行翻译并更新第二个文本区域。

See the section from the Swing tutorial on How to Write a DocumentListener for the basics to get you started.有关入门的基础知识,请参阅 Swing 教程中有关如何编写 DocumentListener的部分。

To reflect changes in one document onto another document you can use a DocumentListener as suggested by camickr .为了反映一个文档中的更改到另一个文档,你可以使用DocumentListener所建议camickr
The following is an mre that demonstrates updating the "output" JTextArea after processing the changes in the "input" JTextArea .下面是一个MRE用于演示在更新“输出” JTextArea处理中的“输入”更改后JTextArea
The processing used for demonstration purposes is a simply converting the input to upper case.用于演示目的的处理只是将输入转换为大写。 This should be changed to your specific needs :这应该根据您的特定需求进行更改:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class MyWindow extends JPanel {

    private static final int ROWS = 10, COLS = 50;

    private final JTextArea outputTextArea;

    public MyWindow() {
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

        JTextArea inputTextArea = new JTextArea(ROWS, COLS);
        inputTextArea.getDocument().addDocumentListener(new TransliterateDocumentListener());
        add(putInTitledScrollPane(inputTextArea,"Input"));

        outputTextArea = new JTextArea(ROWS, COLS);
        outputTextArea.setFocusable(false);
        outputTextArea.setEditable(false);

        add(putInTitledScrollPane(outputTextArea, "Output"));
    }


    private JPanel putInTitledScrollPane(JComponent component, String title) {
        JPanel wrapperPanel = new JPanel(new BorderLayout());
        wrapperPanel.setBorder(BorderFactory.createTitledBorder(title));
        wrapperPanel.add(new JScrollPane(component));
        return wrapperPanel;
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Document Listener Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add( new MyWindow());
        frame.pack();
        frame.setVisible(true);
    }


    private void insert(String text, int from) {
        text = process(text);
         try {
            outputTextArea.getDocument().insertString(from, text, null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }

    private void remove(int from, int length) {
         try {
            outputTextArea.getDocument().remove(from, length);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }

    private String process(String text) {
        //todo process text as needed
        //returns upper case text for demo
        return text.toUpperCase();
    }

    class TransliterateDocumentListener implements DocumentListener {

        @Override
        public void insertUpdate(DocumentEvent e) {
            Document doc = e.getDocument();
            int from = e.getOffset(), length = e.getLength();
            try {
                insert(doc.getText(from, length), from);
            } catch (BadLocationException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            remove(e.getOffset(), e.getLength());
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
             //Plain text components don't fire these events.
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM