user7108016
user7108016

Reputation:

Need my GUI to read from a JTextField and show in a JPanel

I have added an action listener to the text field. When the btnReadString (Button Read String) is pressed the program should read what is on the text field and show on the JPanel. but nothing shows on the panel.

stringTextField.addActionListener(new ActionListener() {
    public void stringTextField (java.awt.event.ActionEvent e) {
        if(e.getSource()==btnReadString) //when the button is pressed
        {
            String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
            textPane.setText(stringParameter);//the JPanel is set to what is on the string. 
            }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
});

Upvotes: 0

Views: 30

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347334

The functionality for the ActionListener should go in the actionPerformed method, as nothings calling the stringTextField method...

stringTextField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==btnReadString) //when the button is pressed
        {
            String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
            textPane.setText(stringParameter);//the JPanel is set to what is on the string. 
        }
    }
});

But, based on the code, the ActionListener should be attached to the btnReadString and not the field, as the above logic will never result in anything been executed (as the source of the event will never be btnReadString)

btnReadString.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
        textPane.setText(stringParameter);//the JPanel is set to what is on the string. 
    }
});

I would suggest having a closer look at How to Write an Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons for more details

Upvotes: 1

inquizitive
inquizitive

Reputation: 632

You have added the ActionListener to the text field. So the event source is never going to be the button and hence, the code is never going to execute. What you want is to add the ActionListener to the JButton.

Also, the actionPerformed() is there for a reason. All your 'action' code goes inside this method.

So your code should look like this:

btnReadString.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {
    String stringParameter = stringTextField.getText();
    textPane.setText(stringParameter);
  }
});

Upvotes: 0

Related Questions