Моя проблема заключается в моем документеListListerListener. Я не могу понять, как передать текст, который пользователь вводит в один из JTextAreas для моих преобразований и возвращает его другому JTextArea.Проблема с передачей ввода от одного JTextArea в другой JTextArea
Цель программы - ввести введенное пользователем римское или арабское число в одном из полей, преобразовать его и вернуть значение преобразования в другое поле в реальном времени.
Мои графические интерфейсы и методы преобразования работают, я просто не могу обернуть голову вокруг получения этой строки от пользователя и печати ее в режиме реального времени.
public class ArabicToRomanGUI_Hard extends JFrame
{
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
//constructor to add text fields to frame
public ArabicToRomanGUI_Hard()
{
JTextArea left = new JTextArea(10, 20);
JTextArea right = new JTextArea(10, 20);
setLayout(new GridLayout(1, 2));
add(new JScrollPane(left));
add(new JScrollPane(right));
MirrorDocument leftDoc = new MirrorDocument();
MirrorDocument rightDoc = new MirrorDocument();
left.setDocument(leftDoc);
right.setDocument(rightDoc);
leftDoc.addDocumentListener(new DocumentHandler(rightDoc));
rightDoc.addDocumentListener(new DocumentHandler(leftDoc));
leftDoc.getDocument().addDocumentListener(AreaListener);
rightDoc.getDocument().addDocumentListener(AreaListener);
}
DocumentListener listener = new DocumentListener()
public class AreaListener implements DocumentListener
{
//DocumentListener listener = new DocumentListener()
@Override
public void changedUpdate(DocumentEvent e)
{
convertInput();
}
@Override
public void insertUpdate(DocumentEvent e)
{
convertInput();
}
@Override
public void removeUpdate(DocumentEvent e)
{
convertInput();
}
private void convertInput(DocumentEvent e)
{
boolean arabicEntered = false;
boolean romanEntered = false;
for (char ch : userInputtedText.toCharArray())
{
if(Character.isLetter(ch))
{
romanEntered = true;
}
if(Character.isDigit(ch))
{
arabicEntered = true;
}
}
if(romanEntered = true)
{
if(ConversionLogic_Hard.getCheckFail() == false)
{
ConversionLogic_Hard.ConvertFromRomanToArabic(userInputtedText); //converts String of RomanNumerals to an arabic int
String arabicNumberAsString = ConversionLogic_Hard.getConvertedRomanNumeral(); //converts number from int to string
}
}
if(arabicEntered == true)
{
if(ConversionLogic_Hard.getCheckFail() == false)
{
ConversionLogic_Hard.ConvertFromArabicToRoman(userInputtedText); //converts String arabicNumberal to String roman numberal
String romanNumberalAsString = ConversionLogic_Hard.getConvertedRomanNumeral(); //gets romanNumberal as String
}
}
}//end convertInput
}//end AreaListener
//creates a flag to test the state of the TextArea
public class MirrorDocument extends PlainDocument
{
private boolean ignoreUpdatedText;
public void setIgnoreUpdates(boolean ignoreUpdatesText)
{
this.ignoreUpdatedText = ignoreUpdatesText;
}
public boolean isIgnoreUpdates()
{
return ignoreUpdatedText;
}
}
//when an event occurs checks the ignoreUpdatedText flag of the document to check if it is false.
//then sets the flag in the checkdocument to true to prevent the document listener from processing any new events.
//then updates the checkdocument.
public static class DocumentHandler implements DocumentListener
{
private MirrorDocument checkDocument;
private boolean ignoreUpdatedText = false;
private JTextArea leftdoc, rightdoc;
boolean arabicEntered = false;
boolean romanEntered = false;
public DocumentHandler(MirrorDocument checkDocument)
{
this.checkDocument = checkDocument;
}
@Override
public void removeUpdate(DocumentEvent e)
{
Document doc = e.getDocument();
if (doc instanceof MirrorDocument)
{
MirrorDocument mirrordoc = (MirrorDocument) doc;
if (!mirrordoc.isIgnoreUpdates())
{
try
{
checkDocument.setIgnoreUpdates(true);
checkDocument.remove(e.getOffset(), e.getLength());
}
catch (BadLocationException exc)
{
exc.printStackTrace();
}
finally
{
checkDocument.setIgnoreUpdates(false);
}
}
}
}//End removeUpdate
@Override
public void changedUpdate(DocumentEvent e)
{
//NOT USED
}
@Override
public void insertUpdate(DocumentEvent e)
{
Document doc = e.getDocument();
if (doc instanceof MirrorDocument)
{
MirrorDocument mirrordoc = (MirrorDocument) doc;
if(!mirrordoc.isIgnoreUpdates())
{
try
{
String textInput = e.getDocument().getText(e.getOffset(), e.getLength());
checkDocument.setIgnoreUpdates(true);
checkDocument.insertString(e.getOffset(), textInput, null);
}
catch(BadLocationException exc)
{
exc.printStackTrace();
}
finally
{
checkDocument.setIgnoreUpdates(false);
}
}
}
}//End insertUpdate
}
}//class
Вы не должны пытаться сделать преобразование внутри DocumentListener, но должны быть используя DocumentFilter, у меня есть решение для этого, на моей работе ПК: P – MadProgrammer
Это тоже очень сложно, потому что вы хотите, чтобы оба поля могли обновлять каждый из них, заставить его работать, чтобы оставшиеся поля могли обновлять право, T купите, что нужно сделать, чтобы оба обновили друг друга. – MadProgrammer
К сожалению, вы были правы, и я ошибся - пойдите с тем, что рекомендует @MadProgrammer, поверьте мне. –