How can I return a JButton from a function and use it to do an action in a different class, I'm creating a library just for practicing my java skills (I lack this part), and I'm trying to make it simpler for creating JFrames and JButtons by creating Objects and Functions to handle that, the problem is, on Frame.java I'm returning the JButton that was created there and then using it in with an ActionListener
, but the problems are, it neither shows the error nor works, May someone provide me an explanation and, if possible, a solution?
Ctrl + F:9812934
|to switch from where I return the JButton and where I use it.
Main.java
package twopackages;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import lib.Button;
import lib.Frame;
public class Main extends Frame{
public static void main(String[] args ){
Frame frame = new Frame();
Button button = new Button();
frame.width = 400;
frame.height = 300;
frame.title = "title";
frame.visible = true;
button.width = 100;
button.height = 30;
button.title = "button";
button.top = 10;
button.left = 10;
button.visible = true;
frame.addButton(button);
frame.run();
frame.addButton(button).addActionListener(new ActionListener() {//Get JButton returned after calling function (I know it's crappy, but I could not find a way to do something similar) 9812934
public void actionPerformed(ActionEvent arg0) {
System.out.println("sadasdasd");
}
});
}
}
Frame.java
package lib;
import javax.swing.JButton;
import javax.swing.JFrame;
import lib.Button;
public class Frame {
public int width;
public int height;
public String title;
public boolean visible;
JFrame FRAME = new JFrame();
public void run(){
FRAME.setSize(width, height);
FRAME.setTitle(title);
FRAME.setLayout(null);
FRAME.setLocationRelativeTo(null);
FRAME.setVisible(visible);
FRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FRAME.setResizable(false);
}
public JButton addButton(Button button){
JButton BUTTON = new JButton();
BUTTON.setText(button.title);
BUTTON.setBounds(button.left, button.top, button.width, button.height);
BUTTON.setVisible(button.visible);
FRAME.add(BUTTON);
return BUTTON;//Here's where I return the JButton 9812934
}
}
Button.java
package lib;
import javax.swing.JButton;
public class Button{
public int left;
public int top;
public int width;
public int height;
public String title;
public boolean visible;
JButton button = new JButton();
public void button(){
button.setBounds(left, top, width, height);
button.setText(title);
button.setVisible(visible);
}
}