PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, June 26, 2022

[FIXED] How can code use an object inside a button?

 June 26, 2022     class, compiler-errors, java, jbutton, swing     No comments   

Issue

I have an issue. I want to use my object which is outside a button, and I get an error message:

Local variable es defined in an enclosing scope must be final or effectively final
File inputfile = new File("./input.txt");
testobject to = null;
try {
    Scanner inputscan = new Scanner(inputfile);
    String text1 = inputscan.nextLine();
    String text2 = inputscan.nextLine();
    to = new testobject(text1,text2);

    inputscan.close();
} catch (Exception e)  {
    System.err.println(e);
}

JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        to.setSomething("test");
    }
});

Obviously, I have a class with a constructor etc... but I have a problem that I cant reach my object inside the button.


Solution

I tried the first method, maybe I did something worng but it didn't work. The second method is working, but this create a new object in the button, so if I want to use outside a button, I need to set everything again. And in my program it is very complicated etc...

So the solution I created an Arraylist and I can use this inside and outside the button too.

ArrayList<testobject> list = new ArrayList<testobject>();

And after this I set the first (0) element to my data

list.add(new testobject(text1,text2));

And after this I can easily use easily the methods of the class

list.get(0).setSomething("test");


Answered By - copy14
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing