Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Where does the program start?

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Where does the program start?

    Hi all,
    I am a newbie to java and hence I have been using online examples to learn how to code java. One big problem I am having is where in the code does the program actually start. I have a java swing code in which I want to call a subroutine to read in some settings from a text file on start up either before or just after the main frame is set visible.

    eg

    private void someroutine(){
    }

    I have tried to call the routine from various locations in the main statement below but I get is the error
    "non-static method readSettings() cannot be referenced from a static context"

    Any help will be apprieciated.


    public static void main(String args[]) {
    /*
    * Set the Nimbus look and feel
    */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
    * If Nimbus (introduced in Java SE 6) is not available, stay with the
    * default look and feel. For details see
    * How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)
    */
    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClass Name());
    break;
    }
    }
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(ContactEditorUI .class.getName()).log(java.util.logging.Level.SEVE RE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(ContactEditorUI .class.getName()).log(java.util.logging.Level.SEVE RE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(ContactEditorUI .class.getName()).log(java.util.logging.Level.SEVE RE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(ContactEditorUI .class.getName()).log(java.util.logging.Level.SEVE RE, null, ex);
    }
    //</editor-fold>

    /*
    * Create and display the form
    */
    java.awt.EventQueue.invokeLater(new Runnable() {

    @Override
    public void run() {
    new ContactEditorUI().setVisible(true);

    }
    });
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,261
    Thanks
    176
    Thanked 818 Times in 761 Posts
    Blog Entries
    5

    Default Re: Where does the program start?

    For future reference, please wrap your code in the [highlight=java][/highlight] tags. Are you just asking how to run that method from the main method? The main method is static, thus if one tries to directly call a method that method must either be called on an object or it must be static. And a minor terminology point, in java they are called methods rather than routines/subroutines.

  3. #3
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Where does the program start?

    yes I want to call it from within the main method, I call call it from a button click ok but it needs to be called when the code starts.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,261
    Thanks
    176
    Thanked 818 Times in 761 Posts
    Blog Entries
    5

    Default Re: Where does the program start?

    Quote Originally Posted by CrestaMan View Post
    yes I want to call it from within the main method, I call call it from a button click ok but it needs to be called when the code starts.
    Then you can define it as static, or create an instance of the Class that contains the method and call the method on that object.

  5. #5
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Where does the program start?

    I have tried private static void somerouine() but netbeans compalined :-(

    Java is by far the hardest language I have had to learn and I just can't get to grips with it's structure.

    any way how do I delare to method and where do I call it from within the main method?

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,261
    Thanks
    176
    Thanked 818 Times in 761 Posts
    Blog Entries
    5

    Default Re: Where does the program start?

    but netbeans compalined
    You should let us know what all the error messages are, or else we're just guessing - my guess is that since the method is as you wrote is private, it is probably in a separate class and thus the main method cannot access the method. Try definine the method as public

  7. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,616
    Thanks
    25
    Thanked 321 Times in 299 Posts

    Default Re: Where does the program start?

    CrestaMan, what languages have you learnt? Java is not a difficult language once you get used to the structure. It might be easier for you to learn java if we compare it to other languages that you have learnt.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #8
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Where does the program start?

    I have declared it a public static void but now netbeans complains about all the variables I am using

    non-static variable xxxxx cannot be referenced from a static context

  9. #9
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,616
    Thanks
    25
    Thanked 321 Times in 299 Posts

    Default Re: Where does the program start?

    Yeah, that'll happen. It has to do with what the word static means. I don't know about what others do, but it is for that reason that I try to limit the amount I do in the main. For example, if I was creating a class that had the main, I would do something like:
    public class SomeClass {
     
    	private int var = 0;
     
    	public SomeClass(int value) {
    		var = value;
    	}
     
    	public int getVar() {
    		return var;
    	}
     
    	public static void main(String[] args) {
    		SomeClass obj = new SomeClass(5);
    		System.out.println("Var value: "+obj.getVar());
    	}
    }

    By creating an Object, doing all of the work in the Object instead of the main, and then creating that Object in the main, you can avoid all of that static nonsense.
    Last edited by aussiemcgr; May 10th, 2012 at 11:33 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  10. #10
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Where does the program start?

    Quote Originally Posted by aussiemcgr View Post
    Yeah, that'll happen. It has to do with what the word static means. I don't know about what others do, but it is for that reason that I try to limit the amount I do in the main. For example, if I was creating a class that had the main, I would do something like:
    public class SomeClass {
     
    	private int var = 0;
     
    	public SomeClass(int value) {
    		var = value;
    	}
     
    	public int getVar() {
    		return var;
    	}
     
    	public static void main(String[] args) {
    		Someclass obj = new SomeClass(5);
    		System.out.println("Var value: "+obj.getVar());
    	}
    }

    By creating an Object, doing all of the work in the Object instead of the main, and then creating that Object in the main, you can avoid all of that static nonsense.
    Ok the main method in my code displays the java swing frame but all I want to do is call one method before to read in some setting from a text file so they can be displayed when the frame is made visible.

    eg.
    program starts
    call the getsettings method
    display the frame

  11. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,616
    Thanks
    25
    Thanked 321 Times in 299 Posts

    Default Re: Where does the program start?

    Every method you call, and every outside variable you reference, inside of a static method MUST be static.

    So, if I had that same example and didn't create a new Object, I would say:
    public class SomeClass {
     
    	public static int var = 0;
     
    	public static int getVar() {
    		return var;
    	}
     
    	public static void main(String[] args) {
    		var = 5;
    		System.out.println("Var value: "+getVar());
    	}
    }

    The main is a static method, therefore the var variable needs to be static (since I make the call var = 5;) and the getVar() method needs to be static (since I call it from the main).
    Last edited by aussiemcgr; May 10th, 2012 at 11:40 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. #12
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Where does the program start?

    heres the chunk of code in question

        public void readSettings() {
     
            try{
                // Open the file that is the first 
                // command line parameter
                FileInputStream fstream = new FileInputStream("c:\\settings.txt");
                // Get the object of DataInputStream
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                //Read File Line By Line
                server = br.readLine();
                userName = br.readLine();
                module = br.readLine();
                port = Integer.parseInt(br.readLine());
                source1 = br.readLine();
                source2 = br.readLine();
                log = br.readLine();
                passwordFile = br.readLine();
                //Close the input stream
                in.close();
            }catch (Exception e){
                }
     
            // Dispaly setings in text boxes
            jTextServer.setText(server);
            jTextUserName.setText(userName);
            jTextModule.setText(module);
            jTextPort.setText(Integer.toString(port));
            jTextSource1.setText(source1);
            jTextSource2.setText(source2);
     
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url]
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
     
                @Override
                public void run() {
                    new ContactEditorUI().setVisible(true);
     
                }
            });
        }

    how do i implement calling getsettings() method in the main method? Sorry for being a pain but I am having trouble with how call methods and classes in java, perhaps I should have stuck with C..

  13. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,616
    Thanks
    25
    Thanked 321 Times in 299 Posts

    Default Re: Where does the program start?

    Do you mean readSettings() (not getsettings())?

    To call it from the main, you need to make readSettings() static, by saying: public static void readSettings(). From there, since the readSettings() method is now static, you need to make all the outside variables it references static aswell, so your variables: server, userName, module, port, source1, source2, log, passwordFile, jTextServer, jTextUserName, jTextModule, jTextPort, jTextSource1, and jTextSource2 all need to be static.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. How to start
    By ashwinjava in forum Member Introductions
    Replies: 2
    Last Post: January 29th, 2012, 03:03 PM
  2. Where do i start?
    By cejay in forum Java Theory & Questions
    Replies: 9
    Last Post: September 10th, 2011, 04:21 PM
  3. [SOLVED] Program to find how many letters start with vowels
    By Lokesh in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 14th, 2011, 04:58 AM
  4. newbie start java program with switches
    By fortune2k in forum Java Theory & Questions
    Replies: 4
    Last Post: November 1st, 2010, 05:13 PM
  5. Where to start?
    By tonykasdorf in forum Java Theory & Questions
    Replies: 3
    Last Post: March 4th, 2010, 10:52 PM