Search code examples
javaswingjtextfieldjtextarea

Getting user input from JtextArea


public static void main(String[] args) throws IOException {
    //cevir("ornek3.txt");
    JFrame frame=new JFrame("Print");
    JPanel input=new JPanel();
    JPanel output=new JPanel(); output.setBackground(Color.black);
    final JTextArea ita = new JTextArea(30, 40);
    JScrollPane ijp = new JScrollPane(ita);
    JTextArea ota = new JTextArea(30, 40);
    JScrollPane ojp = new JScrollPane(ota);
    JButton buton=new JButton("Print");

    frame.setLayout(new FlowLayout());
    buton.setSize(50, 20);
    input.setBounds(0,0,500, 500);
    output.setBounds(500, 0, 500, 450);
    frame.setBounds(100, 50, 1000, 500);


    input.add(ijp, BorderLayout.CENTER);
    output.add(ojp, BorderLayout.EAST);
    input.add(buton, BorderLayout.SOUTH);
    frame.add(input);
    frame.add(output);

    buton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            for(String line: ita.getText().split("\\n"));
                System.out.println(line);


        }
    });


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

This is my code and i want to get the text that i wrote while the program running and print it to the console. Is it possible with JtextArea. This code prints null when i clicked the button to the console even if i write something to the textarea.


Solution

  • You have use the JtextArea#append method.

            public void actionPerformed(ActionEvent e) {
    
                for(String line: ita.getText().split("\\n"))
                   ota.append(line);
    
    
            }
    

    Also variables used inside the methods inner class should be final, so make ota as final

        final JTextArea ota = new JTextArea(30, 40);