- Accessing objects made in main method from other classes
- public static void main(String[] args) {
- Mainframe mainframe = new Mainframe();
- mainframe.initialiseMF();
- LoginPanel lp = new LoginPanel();
- mainframe.add(lp);
- }
- public class Mainframe extends JFrame {
- public Mainframe () {
- // Set size of mainframe
- setBounds(0, 0, 500, 500);
- }
- public void initialiseMF (){
- // Get the size of the screen
- Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
- // Determine the new location of the mainframe
- int w = getSize().width;
- int h = getSize().height;
- int x = (dim.width-w)/2;
- int y = (dim.height-h)/2;
- // Move the mainframe
- setLocation(x, y);
- setVisible(true);
- }
- Container content = mainframe.getContentPane();
- public class Mainframe extends JFrame{
- public Mainframe(){
- initialiseMF ();
- }
- public void initialiseMF (){
- //do ur inits here
- }
- }
- public class TheOtherClass{
- private Mainframe mainFrame;
- public TheOtherClass(){
- mainFrame = MainFrame.mainFrame; //although I would not suggest this, it will avoid the Main.mainFrame call
- }
- public void otherMethodFromOtherClass(JFrame mainFrame){
- Container content = mainFrame.getConentPane();
- }
- }
- //local variables are the ones that are declared inside a method
- //their life and visibility is limited only within the block in which they are define.
- public static void main(String[] args) { // args is also a local variable
- String localVar = "Access modifiers are not allowed for local variables.";
- //the reason that the access modifiers are not allowed is because
- //the local variables are not members of the class
- }
- class AClass {
- private String memberVar = "A member variable can have access modifier.";
- //the access modifier will determine the visibility of that variable.
- public String getMemberVar() {
- return this.memberVar;
- }
- }