getText() causes Exception

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Akino877
    New Member
    • Nov 2007
    • 37

    getText() causes Exception

    Hello,

    I am writing a simple Java program that has 2 buttons and 1 text field. How
    I would like for it to work is that when I click on Button 1, the actionPeformed
    method would get the text from the text field and then change the text of
    Button 2 to this text (in the text field). And when I click on Button 2, the
    actionPeformed method would get the text from the text field and change
    the text of Button 1 to this text.

    When I run my program the text of the button does not change as intented
    and I got error from the screen :

    Exception in thread "AWT-EventQueue-0" java.lang.NullP ointerException
    at ButtonPanel.act ionPerformed(Bu ttonTest.java:3 3)
    at javax.swing.Abs tractButton.fir eActionPerforme d(AbstractButto n.java:1995)

    My code is as follows :import java.awt.*;
    import java.awt.event. *;
    import javax.swing.*;

    class ButtonPanel extends JPanel implements ActionListener
    {
    public ButtonPanel()
    {
    button1 = new JButton("Button 1");
    button2 = new JButton("Button 2");

    JTextField chrisField = new JTextField("Hel lo", 20);

    setLayout (new FlowLayout(Flow Layout.LEFT));

    add(button1);
    add(button2);
    add(chrisField) ;

    button1.addActi onListener(this );
    button2.addActi onListener(this );
    chrisField.addA ctionListener(t his);
    }public void actionPerformed (ActionEvent evt)
    {
    Object source = evt.getSource() ;

    if (source == button1)
    {
    /* button2.setText ("Hello There"); */
    String text = chrisField.getT ext().trim();
    button2.setText (text);
    }
    else if (source == button2)
    {
    /* button1.setText ("Hello There"); */
    String text = chrisField.getT ext().trim();
    button1.setText (text);
    }
    }

    private JButton button1;
    private JButton button2;
    private JTextField chrisField;
    }class ButtonFrame extends JFrame
    {
    public ButtonFrame()
    {
    setTitle("Butto nTest");
    setSize(300, 200);
    addWindowListen er(new WindowAdapter()
    { public void windowClosing(W indowEvent e)
    { System.exit(0);
    }
    } );

    Container contentPane = getContentPane( );
    contentPane.add (new ButtonPanel());
    }
    }

    public class ButtonTest
    {
    public static void main(String[] args)
    { JFrame frame = new ButtonFrame();f rame.show();
    }
    }

    Your help is much appreciated.

    Akino.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Have another look at the constructor of your ButtonPanel: you assign that
    JTextField to a local variable 'chrisField' that hides your member variable with
    the same name. It'll stay null forever.

    btw, the 'show()' method of your frame is deprecated, use pack() and setVisible(true )
    instead.

    kind regards,

    Jos

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      You should take a look at the Sun tutorials:

      [http://java.sun.com/docs/books/tutorial/]

      Including this GUI HelloWorld:

      [http://java.sun.com/docs/books/tutorial/uiswing/examples/start/index.html]


      You don't need to use a WindowListener to shut a window and you should learn about invokeLater, too...

      Comment

      • tburger
        New Member
        • Jul 2007
        • 58

        #4
        I also don't think there is a need for an action listener on the text field. No behaviors are triggered by the text field changing, only when a button is clicked.

        Tom

        Comment

        • BigDaddyLH
          Recognized Expert Top Contributor
          • Dec 2007
          • 1216

          #5
          Originally posted by tburger
          I also don't think there is a need for an action listener on the text field. No behaviors are triggered by the text field changing, only when a button is clicked.

          Tom
          Then why would JTextField define the method addActionListen er? In fact, this is a very useful feature. The listener is notified when enter is pressed whilst focus is on the text field. The text in the text field is passed as the action command of the ActionEvent. Demo:

          [CODE=Java]import java.awt.*;
          import java.awt.event. *;
          import javax.swing.*;

          public class JTextFieldActio nListenerExampl e {
          private ActionListener al = new ActionListener( ) {
          public void actionPerformed (ActionEvent evt) {
          System.out.prin tln(evt.getActi onCommand());
          }
          };

          public void go() {
          JTextField text = new JTextField(20);
          text.addActionL istener(al);

          JFrame f = new JFrame();
          f.setDefaultClo seOperation(JFr ame.EXIT_ON_CLO SE);
          f.getContentPan e().add(text, BorderLayout.NO RTH);
          f.pack();
          f.setLocationRe lativeTo(null);
          f.setVisible(tr ue);
          }

          public static void main(String[] args) {
          EventQueue.invo keLater(new Runnable() {
          public void run() {
          new JTextFieldActio nListenerExampl e().go();
          }
          });
          }
          }[/CODE]

          Comment

          • Kid Programmer
            New Member
            • Mar 2008
            • 176

            #6
            You could try approaching the problem a different way and instead of making one event create 2 events for each button. Do something like this for each button:
            Code:
            button1.addActionListener(new ActionListener()
            {
            	public void actionPerformed(ActionEvent button1)
            	{
            		String value = chrisField.getText();
            		button2.setText(value);
            	}
            });
            Then create another one for button2. I didn't test that little code snippet because I'm lazy but that should just give you an idea of what to do.

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by Kid Programmer
              Then create another one for button2. I didn't test that little code snippet because I'm lazy but that should just give you an idea of what to do.
              Did you read reply #2? It explains the error; no need to add two listeners because
              it doesn't solve the op's problem.

              kind regards,

              Jos

              Comment

              • Kid Programmer
                New Member
                • Mar 2008
                • 176

                #8
                Originally posted by JosAH
                Did you read reply #2? It explains the error; no need to add two listeners because
                it doesn't solve the op's problem.

                kind regards,

                Jos
                I read all the replies. I was just giving him advice. That's how I write my code.
                I create a JFrame, I create a Container, a Layout or I use setBounds, I make my components, I add my components to my Container, I set the actions that they preform to whatever I want, then I do all my frame setting things like the title and the default close operation. It always works out for me

                Comment

                • tburger
                  New Member
                  • Jul 2007
                  • 58

                  #9
                  Originally posted by BigDaddyLH
                  Then why would JTextField define the method addActionListen er? In fact, this is a very useful feature. The listener is notified when enter is pressed whilst focus is on the text field. The text in the text field is passed as the action command of the ActionEvent. Demo:
                  I understand and agree that this functionality exists and could be used in many situations...

                  I was merely suggesting that an action listener was not needed in the context of the thread's original code, since all the events are triggered by buttons. I wasn't trying to say that no one should ever use an action listener on a text field...

                  Good demo on potential functionality, though. Thanks.

                  Tom

                  Comment

                  • Kid Programmer
                    New Member
                    • Mar 2008
                    • 176

                    #10
                    Originally posted by tburger
                    I understand and agree that this functionality exists and could be used in many situations...

                    I was merely suggesting that an action listener was not needed in the context of the thread's original code, since all the events are triggered by buttons. I wasn't trying to say that no one should ever use an action listener on a text field...

                    Good demo on potential functionality, though. Thanks.

                    Tom
                    No problemo. And here is some code that should make the program work:
                    Code:
                    import javax.swing.*;
                    import java.awt.*;
                    import java.awt.event.*;
                    
                    public abstract class gui implements ActionListener {
                    	
                    	public static void main(String[] args)
                    	{
                    		JFrame frame;
                    		final JButton button1, button2;	
                    		final JTextField textfield;
                    		Container contentPane;
                    		FlowLayout layout;
                    
                    		frame = new JFrame();
                    		
                    		contentPane = frame.getContentPane();
                    
                    		layout = new FlowLayout();
                    		
                    		frame.setLayout(layout);
                    
                    		button1 = new JButton("Button 1");
                    		button2 = new JButton("Button 2");
                    
                    		textfield = new JTextField("Type something here");
                    
                    		contentPane.add(button1);
                    		contentPane.add(button2);
                    		contentPane.add(textfield);
                    
                    		button1.addActionListener(new ActionListener()
                    		{
                    			public void actionPerformed(ActionEvent button1)
                    			{
                    				String value;
                    				value = textfield.getText();
                    				button2.setText(value);
                    			}
                    		});
                    		button2.addActionListener(new ActionListener()
                    		{
                    			public void actionPerformed(ActionEvent button2)
                    			{
                    				String value;
                    				value = textfield.getText();
                    				button1.setText(value);
                    			}
                    		});
                    
                    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    		frame.pack();
                    		frame.setVisible(true);
                    	}
                    }

                    Comment

                    Working...