views:

32

answers:

2

please help me with this code the text is not appearing in textfield although it is through cmd prompt but not in textfield

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

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



public class listener11
{
    private JFrame f;
    private JButton b;
    private JTextField tf;
    public static String str;


    public  listener11()
    {
        f=new JFrame("Listener1");
        b=new JButton("Press");
        b.setActionCommand("Button b1 pressed");
        tf=new JTextField(30);
    }

    public void launchframe()
    {
         f.setLayout(null);
         b.addActionListener(new Buttonlistener());
         b.setBounds(200,200,100,100);
         tf.setBounds(100,100,200,50);
         tf.setText(str);
         f.add(b);
         f.add(tf);
         f.setSize(400,400);

         f.setVisible(true);
    }

    public static void main(String[]arg)
    {
         listener11 l1=new listener11();
         l1.launchframe();
    }
}

class Buttonlistener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        listener11.str="Action took place \n button's command is"+e.getActionCommand();
    }
}
+2  A: 

When the actionPerformed method is invoked, you're just changing the value of the str variable. That doesn't automatically update the text box - just because you've called

tf.setText(str);

doesn't mean it will automatically look at the str variable the whole time. If you want to set the text again, call tf.setText again. (Alternatively, you can get into the whole model/view/controller business which is how Swing is meant to work, but that's considerably more complicated. For the moment you're probably best off sticking to the simple approach.)

Jon Skeet
+1  A: 

Looks like you are only setting the text to null (as str is null in the launchframe() method). You need to call setText with a valid string even though you assign that string later, the text field still has null.

Dave B