Search code examples
javaswingjbuttonactionlistener

JButton in the class and actionlistener on the main


I am new to Java Programming. I would like to create JButton inside the class and create ActionListener in the main by passing button arguments. But it throws an error:

Cannot make a static reference to the non-static field newBtn

My code is as below.

import java.awt.event.*;  
import javax.swing.*;    
public class TestBtn { 

TestBtn() {
}

public void myBtn(JButton mybtn){   
    JFrame f=new JFrame("My Example");   

    mybtn =new JButton("Click Here");  
    mybtn.setBounds(50,100,95,30);  

    f.add(mybtn);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
} 
}

// My Main Program

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;  
public class TestBtnMain {
    JButton newBtn; 

public static void main(String[] args) {
    TestBtn btn = new TestBtn();
    btn.myBtn(newBtn);

    newBtn.addActionListener(new ActionListener(){  
        public void actionPerformed(ActionEvent e){  
            System.out.println("Success");
            }  
        });
}
}

Solution

  • Unlike to C++ Java has no possibility for transfer of parameters by reference. So I would change your code as following:

    import java.awt.event.*;  
    import javax.swing.*;    
    public class TestBtn { 
    
        TestBtn() {
    
        }
        public JButton myBtn(){   
    
            JFrame f=new JFrame("My Example");   
    
            JButton mybtn =new JButton("Click Here");  
            mybtn.setBounds(50,100,95,30);  
    
            f.add(mybtn);  
            f.setSize(400,400);  
            f.setLayout(null);  
            f.setVisible(true);   
            return mybtn;
        } 
    
    }
    

    Main class:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;  
    public class TestBtnMain {
    
        public static void main(String[] args) {
            TestBtn btn = new TestBtn();
            JButton newBtn = btn.myBtn();
    
            newBtn.addActionListener(new ActionListener(){  
                public void actionPerformed(ActionEvent e){  
                    System.out.println("Success");
                }  
            });
    
    
        }
    }
    

    And, as already mentioned by Andrew Thompson, you should use a layout manager to make your UI working with the different platforms/screen resolutions