Java Swing TextArea:如何在输出 TextArea 中同时打印音译 text/s?

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

我正在尝试编写一个文本编辑器。我想要两个 TextAreas:第一个 用于 unicode 脚本中的 typing/editing 和 2nd one 用于同时打印相应的 unicode 脚本输入的输出Roman Script (ASCII) 是我自己在音译方案的基础上设定的。 在调用音译方法时,我无法更新并同时打印输出文本区域中的输入文本。当我将输出 textArea 设置为同时打印时,我能感觉到有一点不对劲,但我无法找出到底是什么。

编辑器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();
                }
            }
        });
    }
}

和音译class方法:


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() 方法所做的只是在多个组件之间共享文档。因此,无论您键入什么,都将显示在两个组件中。

相反,您可以使用 DocumentListener。只要在文档中添加或删除文本,侦听器就会生成一个事件。然后您需要阅读文档中的文本并进行翻译并更新第二个文本区域。

请参阅有关 How to Write a DocumentListener 的 Swing 教程部分,了解入门的基础知识。

要将一个文档中的更改反映到另一个文档中,您可以按照 的建议使用 DocumentListener
以下是一个 mre,演示了在处理 "input" JTextArea.
中的更改后更新 "output" JTextArea 用于演示目的的处理只是将输入转换为大写。这应该更改为您的特定需求:

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());
    }
}