Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle events in Java?

I just made my first event based GUI in java, but i don't understand where i am wrong. the code worked fine when there was no event handling applied..

Here's the code.

package javaapplication1;

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

 class Elem implements ActionListener{

    void perform(){
        JFrame frame = new JFrame();
        JButton button;
        button = new JButton("Button");
        frame.getContentPane().add(button) ;
        frame.setSize(300,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(this);
     }

    public void actionPerformed(ActionEvent ev){
        button.setText("Clicked");
    }
}

 public class JavaApplication1 {

  public static void main(String[] args) {
   Elem obj = new Elem();
   obj.perform();
  }  
}
like image 700
Juzz Coding Avatar asked Jun 27 '26 02:06

Juzz Coding


2 Answers

There is a problem with variable scope. Move the JButton button; definition outside of the perform() method so that actionPerformed() can access it.

JButton button;

void perform(){
    JFrame frame = new JFrame();
    button = new JButton("Button");
    frame.getContentPane().add(button) ;
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    button.addActionListener(this);
 }

When you define an object inside of a method (e.g. perform()), its scope is limited to that method (inside the curly braces). This means that other methods inside your class cannot access that variable.

By moving the object definition outside of the method, it now has class level scope. This means that any method within that class can access the variable. You're still defining its value inside of perform(), but now it can be accessed by other methods, including actionPerformed().

See here for more explanation.

like image 98
ashatte Avatar answered Jun 28 '26 16:06

ashatte


As you used button object inside actionPerformed method. So declare button globally.

class Elem implements ActionListener{
     JButton button;// Declare JButton here.
    void perform(){
        JFrame frame = new JFrame();

        button = new JButton("Button");
        frame.getContentPane().add(button) ;
        frame.setSize(300,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(this);
     }

    public void actionPerformed(ActionEvent ev){
        button.setText("Clicked");
    }
}

 public class JavaApplication1 {

  public static void main(String[] args) {
   Elem obj = new Elem();
   obj.perform();
  }  
}
like image 39
Masudul Avatar answered Jun 28 '26 16:06

Masudul



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!