0

Possible Duplicate:
How to print the user input on screen from a TextField using Java Swing

Please see the code below:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

    public class Swingtest extends JFrame implements ActionListener{
    JTextField txtdata;
    JButton calbtn = new JButton("Calculate");

    public Swingtest()
    {
        JPanel myPanel = new JPanel();
        add(myPanel);
        myPanel.setLayout(new GridLayout(3, 2));
        myPanel.add(calbtn);
        calbtn.addActionListener(this);
        txtdata = new JTextField();
        myPanel.add(txtdata);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == calbtn) {
            String data = txtdata.getText(); //perform your operation
            System.out.println(data);
        }
    }

    public static void main(String args[])
    {
        Swingtest g = new Swingtest();
        g.setLocation(10, 10);
        g.setSize(300, 300);
        g.setVisible(true);
    }
}

What I want to do is display the text entered in the field by the user in the same window. Kinda like with paint(Graphics g) and repaint() when the text is changed. Please help. Thanks.

Community
  • 1
  • 1

2 Answers2

1

Add a JLabel, JTextField, JTextArea or whatever component able to display text. Get the document of the JTextField where the user enters text, and add a DocumentChangeListener to this document. Each time a DocumentEvent is received, get the text from the JTextField and update the text in the JLabel, JTextField, JTextArea or whatever component you chose.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Ok so I can't use something like: void paint(Graphics g){ //print it? } –  Nov 01 '12 at 09:08
  • 1
    You could design your own Swing component that displays a line of text, but why would you, since standard components doing that already exist? – JB Nizet Nov 01 '12 at 09:10
  • Please can u give an example code –  Nov 01 '12 at 16:45
0

This can be done through redirecting the I/O/E streams:

I would have given you an elaborated answer, but the answerer of the answer selected for this question explains it better.

See this question: How could I read Java Console Output into a String buffer

After reading it into a StringBuffer, you can print it onto a JTextField or JTextArea.. etc

Community
  • 1
  • 1
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78