Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 12th, 2012  |  syntax: None  |  size: 1.96 KB  |  hits: 26  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Accessing objects made in main method from other classes
  2. public static void main(String[] args) {
  3.  
  4.     Mainframe mainframe = new Mainframe();
  5.     mainframe.initialiseMF();      
  6.     LoginPanel lp = new LoginPanel();
  7.     mainframe.add(lp);
  8. }
  9.  
  10. public class Mainframe extends JFrame {
  11.  
  12. public Mainframe () {
  13.     // Set size of mainframe
  14.     setBounds(0, 0, 500, 500);
  15.  
  16. }
  17.  
  18. public void initialiseMF (){
  19.     // Get the size of the screen
  20.     Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
  21.  
  22.     // Determine the new location of the mainframe
  23.     int w = getSize().width;
  24.     int h = getSize().height;
  25.     int x = (dim.width-w)/2;
  26.     int y = (dim.height-h)/2;
  27.  
  28.     // Move the mainframe
  29.     setLocation(x, y);
  30.     setVisible(true);
  31. }
  32.        
  33. Container content = mainframe.getContentPane();
  34.        
  35. public class Mainframe extends JFrame{
  36.      public Mainframe(){
  37.           initialiseMF ();
  38.      }
  39.  
  40.      public void initialiseMF (){
  41.           //do ur inits here
  42.      }
  43.  
  44. }
  45.        
  46. public class TheOtherClass{
  47.  
  48.     private Mainframe mainFrame;
  49.  
  50.     public TheOtherClass(){
  51.         mainFrame = MainFrame.mainFrame; //although I would not suggest this, it will avoid the Main.mainFrame call
  52.     }
  53.  
  54.     public void otherMethodFromOtherClass(JFrame mainFrame){
  55.         Container content = mainFrame.getConentPane();
  56.     }
  57. }
  58.        
  59. //local variables are the ones that are declared inside a method
  60. //their life and visibility is limited only within the block in which they are define.
  61. public static void main(String[] args) { // args is also a local variable
  62.     String localVar = "Access modifiers are not allowed for local variables.";
  63.     //the reason that the access modifiers are not allowed is because
  64.     //the local variables are not members of the class        
  65. }
  66.        
  67. class AClass {
  68.     private String memberVar = "A member variable can have access modifier.";
  69.     //the access modifier will determine the visibility of that variable.
  70.  
  71.     public String getMemberVar() {
  72.         return this.memberVar;
  73.     }
  74. }