Home > Back-end >  How do I make variables accessible everywhere?
How do I make variables accessible everywhere?

Time:11-03

I am using java swing and I have tried using new text as a parameter but I am not sure how, there is also the fact that I have "});" which is completely messed up but it works, and i tried fixing it and it doesn't work

this code is inside my main

public String newText = "";

a.addActionListener(new ActionListener() {

  public void actionPerformed(ActionEvent ae) {
    JFrame popup = new JFrame("Choose...");
    popup.setSize(250,250);
    popup.setLayout(null);
    popup.setVisible(true);
    JButton o=new JButton("o");
    o.setBounds(25,75,100,100); 
    popup.add(o);
    o.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae, String newText){
        newText = "O";
      }
    });
    JButton x=new JButton("x"); 
    x.setBounds(125,75,100,100);  
    popup.add(x);
    if (!newText.equals(""))
        a.setText(newText);
  }
});

CodePudding user response:

I have tried using newText as a parameter

Here?

public void actionPerformed(ActionEvent ae, String newText){

This is not valid code. ActionListener is an interface; an interface is a contract that must be followed. You cannot simply add variables to existing method signatures.

Assuming you wanted to modify the button text, you could do this

public class Main {

    public String newText;

    public static void main(String[] args) {
       new Main().run();
    }

    public void run() {

        System.out.printf("before: newText = %s%n", newText);
        final JButton o = new JButton("o");
        // ...
        o.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                Main.this.newText = "O"; // Sets the field
                System.out.printf("action: newText = %s%n", Main.this.newText);
                o.setText(Main.this.newText);
            }
        });
        System.out.printf("actionListener set : newText = %s%n", newText);
    }
}

However, trying to use newText.equals outside of the action listener happens on a different thread, meaning the code does not run "top to bottom". E.g. the variable isn't "set" in the execution order that the code reads as. Added print statements to show this

  • Related