Harish Ved
Harish Ved

Reputation: 570

How to change text in text-field from inner-class??

I wanted to change text in a JTextField by using actionlistener on a button. there is a radiobutton group and Sort.SWITCH changes its value according to radiobutton selected.

So when sort button is pressed the text in Output field must change from "Output" to "Some text".. but the error is that Output field cannot be accessed from innerclass. Plz tell me the proper way to do that. thanks..

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

 class Sort extends JFrame
 {
     ...
 }
 class q2 extends Sort
 {
     public static void main(String[] args)
     {
             ...
             JTextField Output = new JTextField(50);
             Output.setText("Output");
             ResultPanel.add(Output);
             SortButton.addActionListener(new ActionListener() {

                 public void actionPerformed(ActionEvent a)
                 {
                       if (Sort.SWITCH == 1)
                       {
                          Output.setText("Some Text");
                       }
                       else if ...
                       ...
                 } });
            }}

Upvotes: 0

Views: 1689

Answers (2)

Eng.Fouad
Eng.Fouad

Reputation: 117597

Define Output as a class field:

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

 class Sort extends JFrame
 {
     ...
 }
 class q2 extends Sort
 {
     public JTextField Output;
     public static void main(String[] args)
     {
             ...
             Output = new JTextField(50);
             Output.setText("Output");
             ResultPanel.add(Output);
             SortButton.addActionListener(new ActionListener() {

                 public void actionPerformed(ActionEvent a)
                 {
                       if (Sort.SWITCH == 1)
                       {
                          Output.setText("Some Text");
                       }
                       else if ...
                       ...
                 } });
     }
 }

Upvotes: 2

Mark Elliot
Mark Elliot

Reputation: 77044

To access your variable from inside the anonymous class, define the variable as a field (instead of a local variable), or as final:

public static void main(String[] args){
    //...
    final JTextField Output = new JTextField(50);

Anonymous inner-classes may only access fields or final variables from the defining class.

Upvotes: 2

Related Questions