Search code examples
javaswingjframejtextarea

converting from JTextArea to String and back


For a homework assignment I am tasked with determine how many of each letter are in a sentence. I have already successfully completed the homework using JOptionPane. But I want to display in a JFrame. I am able to convert from the text area input, but am no table to convert from string back to text area display.

:

for (short i = 0; i < (output).length(); i++)
                {
                    char temp = Character.toLowerCase((output).charAt(i));
                    if (temp >= 'a' && temp <= 'z')
                        counts[temp - 'a']++;
                }

                for (short i = 0; i < counts.length; i++)
                {
                    output += (char) ('a' + i) + ":\t " + counts[i] + "\n";
                }

                for (short i = 0; i < (input).length(); i++)
                {
                    if ((output).charAt(i) == 'a' || (output).charAt(i) == 'A')
                        count++;
                }
                txaResults.setText(output);

Solution

  • Try and put the createAndShowGUI before the frame.setVisible. You're making the frame visible before your method can perform.

    I think this may be your problem:

    // You're doing this
    output = txaResults.getText();
    
    // but I think you want this
    input = txaUserInput.getText();
    
    String output = "";
    
    // Your logic here
    ...
    ...
    
    txaResults.setText(output);
    

    You need to perform the logic from the txaUserInput and display it in the txaResults

    Edit: try this for your logic

           int[] counts = new int[26];
           for (short i = 0; i < (input).length(); i++)
    
           {
                    char temp = Character.toLowerCase((input).charAt(i));
                    if (temp >= 'a' && temp <= 'z')
                        counts[temp - 'a']++;
           }
    
    
           for (short i = 0; i < counts.length; i++)
           {
                   output += (char) ('a' + i) + ":\t " + counts[i] + "\n";
           }
    
           int count = 0;
           for (short i = 0; i < (input).length(); i++)
           {
                    if ((input).charAt(i) == 'a' || (input).charAt(i) == 'A')
                        count++;
           }
    
           output += "" + count;
           txaResults.setText(output);