Search code examples
javaswingjbutton

java JButton setEnabled isn't working properly


I have a JButton that is setEnabled(false) as default, and then if a condition from another class is true, that button will be enabled, but the button isn't being enabled at all. All 3 classes are from the same package.

Main.java(main class)

import javax.swing.JFrame;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        OtherClass c1 = new OtherClass();
        Panel p = new Panel();
        frame.add(p);
        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        //p.setButtonEnabled();
    }
    
}

Panel.java

import javax.swing.JButton;
import javax.swing.JPanel;

public class Panel extends JPanel{
    JButton b1 = new JButton("OK"); ;
    
    public Panel(){
        b1.setSize(50, 50);
        b1.setEnabled(false);
        add(b1);
    }
    
    public void setButtonEnabled(){
        b1.setEnabled(true);
    }
}

OtherClass.java

public class OtherClass {
    Panel p1 = new Panel();
    
    //some method
    public void method(){ 
        if (true){
            p1.setButtonEnabled();
        }
    }
}

But when I called the setButtonEnabled() method from the main method, it somehow worked, can someone explain why and how to fix it, I just learned Java for about a month and this is my first time using Swing, thanks a lot.


Solution

  • The button's state remains unaffected because setButtonEnabled() is invoked on a separate instance of Panel, which doesn't reflect the instance added to the frame in the main method.

    public class Main {
    
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            Panel p = new Panel();
            OtherClass c1 = new OtherClass(p); // Pass the Panel instance to OtherClass
            frame.add(p);
            frame.setSize(300, 300);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }
    
    public class OtherClass {
        private Panel p1;
    
        public OtherClass(Panel p1) {
            this.p1 = p1;
        }
        
        public void method(){ 
            if (true){
                p1.setButtonEnabled();
            }
        }
    }