Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swing- perform an action on click

Tags:

java

swing

I think I've coded myself into a bit of a corner here. I am trying to do something to this effect using java swing.

On click of the button next, load a new line from a file (via line index number), then if the date from the line in the file has not yet arrived, grey out the next button. My issue is that when I have the following code:

    Scanner input = new Scanner(System.in);
    System.out.println("Enter week number");
    int j = input.nextInt();
    String[] strArray = new String[4];        
    xmlLoader(j, strArray);

    JButton nextButton = new JButton("Next");
    nextButton.setBounds(750, 250, 80, 30);
    nextButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae){
           j++;
           doNext(j, nextButton);
       } 
    });

I cannot pass the j because it's not final, and I can't change anything on the button if it's final, helpppp!

Specific error: local variable j is accessed from within inner class; needs to be declared final

like image 915
HunderingThooves Avatar asked Sep 15 '26 04:09

HunderingThooves


2 Answers

You may define j as a field in outer class.

class Sample{
   private int j;

   void method() {
     ...
     nextButton.setBounds(750, 250, 80, 30);
     nextButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae){
           j++;
           doNext(j, nextButton);
       }
      });
    }
}
like image 189
KV Prajapati Avatar answered Sep 17 '26 19:09

KV Prajapati


Make the j class field instead of declaring local variable.

like image 45
StanislavL Avatar answered Sep 17 '26 17:09

StanislavL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!