Understanding Use of Static Main Method


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 7 of 7

Thread: Understanding Use of Static Main Method

  1. #1
    Join Date
    May 2006
    Posts
    12

    Understanding Use of Static Main Method

    Hi. I have created a basic class that is shown below. After creating this class I want to test the class out of course. So of course the Java compiler complains to me that non-static variables cannot be referenced from static contexts.
    Ok, so yes this makes sense to me- that is the static vs non-static scenario.

    However, I'm not quite sure how to resolve my problem without making the variables in question "textPanel" and "sendPanel" static. Which I don't want to do, of course.

    I think my ChatOne class design is reasonable but I can't figure how to execute it. Thanks for the advice.

    Code:
    import javax.swing.*;
    import java.awt.*;
    //import java.awt.event.*;
    
    public class ChatOne{
    	JPanel textPanel, sendPanel;
    	JEditorPane textPane;
    	JTextField sendPane;
    	JButton sendBtn;
    	private String frameTitle;
    	private String btnTitle;
    	private final String DEFAULT_MSG = "Welcome to ChatOne!\nHere at ChatOne we're a one-man team.\nYep, we're poor, alright!\nBack off!";
    	
    	public ChatOne(){
    		this("ChatOne!!", "Send Me!");
    	}
    	
    	public ChatOne(String frameTitle){
    		this(frameTitle, "Send!");
    	}
    	
    	public ChatOne(String frameTitle, String btnTitle){
    		this.frameTitle = frameTitle;
    		this.btnTitle = btnTitle;
    	}
    	
    	private void init(){
    		textPane = new JEditorPane("text/html", DEFAULT_MSG);
    		sendPane = new JTextField();
    		sendBtn = new JButton(btnTitle);
    		
    		textPanel = new JPanel();
    		textPanel.add(textPane);
    		
    		sendPanel = new JPanel();
    		sendPanel.add(sendPane);
    		sendPanel.add(sendBtn);
    	}
    	
    	public JPanel getSendPanel(){
    		return sendPanel;
    	}
    	
    	public JPanel getTextPanel(){
    		return textPanel;
    	}
    	
    	public static void main(String[] args){
    		JFrame frame = new JFrame("ChatOne");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setDefaultLookAndFeelDecorated(false);noooo
    		//modify to ratios
    		frame.setSize(300,300);
    		frame.setLocation(200,200);
    		//end modify to ratios
    		
    		frame.setLayout(new FlowLayout());
    
     //NOT ALLOWED
    		frame.getContentPane().add(getTextPanel());
    		frame.getContentPane().add(getSendPanel());
    //END COMPILER ERROR
    		frame.pack();
    		frame.setVisible(true);
    	}
    }

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    In main(), create an instance of ChatOne. - ChatOne myChat = new ChatOne(). You refer to this instance as myChat.

    You are currently creating a JFrame named ChatOne which has nothing to do with the other parts of your ChatOne class. You want to be manipulating the JFrame which is held in an instance of your ChatOne class.

    The stuff currently in your main can be initialized in your construction of myChat, or you can manipulate these features of the myChat.frame by calling myChat.frame.setDefaultCloseOperation ... . etc.

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Statics again...

    Seems I have coded what nspils prescribed...
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class ChatOne extends JFrame {
      private JPanel textPanel, sendPanel;
      private JEditorPane textPane;
      private JTextField sendPane;
      private JButton sendBtn;
      private String frameTitle;
      private String btnTitle;
      private static String DEFAULT_MSG = "Welcome to ChatOne!\nHere at ChatOne we're a one-man team.\nYep, we're poor, alright!\nBack off!";
    
      public ChatOne() {
        this("ChatOne!!", "Send Me!");
        init();
      }
    
      public ChatOne(String frameTitle) {
        this(frameTitle, "Send!");
        init();
      }
    
      public ChatOne(String frameTitle, String btnTitle) {
        this.frameTitle = frameTitle;
        this.btnTitle = btnTitle;
        init();
      }
    
      private void init() {
        textPane = new JEditorPane("text/html", DEFAULT_MSG);
        sendPane = new JTextField();
        sendBtn = new JButton(btnTitle);
    
        textPanel = new JPanel();
        textPanel.add(textPane);
    
        sendPanel = new JPanel();
        sendPanel.add(sendPane);
        sendPanel.add(sendBtn);
    
        getContentPane().setLayout(new FlowLayout());
        // You will have to sort out the layout yourself...
        getContentPane().add(sendPanel);  // etc...
      }
    
      /**
       * The main should only instatiate an instance of your ChatOne (frame) class.
       * The rest of the work is done by the ChatOne class.
       * When statics are used a lot it often indicates a bad program design.
       */
      public static void main(String[] args) {
        ChatOne frame = new ChatOne();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setDefaultLookAndFeelDecorated(false);
        frame.setBounds(200,200,300,300);
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
        frame.setVisible(true);
      }
    }
    eschew obfuscation

  4. #4
    Join Date
    May 2006
    Posts
    12

    Extending JFrame...

    Ok, I see what you have said and that you have extended JFrame so that ChatOne is-a JFrame.

    Now, I have a followup question but first some context:

    I was trying to create a class that was basically just 1/2 JPanels.
    Then in a main of some class, say a loader class, I would just create a JFrame and place the instance of my ChatOne class with in the JFrame.

    Now, to remedy the static vs. non-static problem, ChatOne extended JFrame.
    However, I don't want my ChatOne class to be a JFrame. Furthermore, and to the point finally, I thought that you weren't supposed to extend a class, here it's JFrame, unless you were making significant changes from the superclass.
    I'm talking about the is-a vs. has-a relationship.

    Any more advice?
    Thanks!

  5. #5
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Not quite right.

    I thought that you weren't supposed to extend a class, here it's JFrame, unless you were making significant changes from the superclass.
    Not quite right (who said that ? ). Sounds like something a teacher would say. You add functionality when you extend a class, and sometimes you alter/block out some functionality. Like, in your case, you want to add some components (panels) to it. As it seems, you should make your class an extension of a JPanel with a layout that handles the addition of more panels inside it.

    I have rarely seen java code, except for basic test stubs, that creates bare JFrames and then adds panels and stuff to it inside a loader class of some sort. It doesn't support the idea of encapsulation very well. In my opinion you loose that when the code for construction of a JFrame or JPanel is coded outside the frame/panel class in some code fragment of another class, including the frame's/panel's eventhandling and methods. It easily gets messy and hard to debug and maintain.
    Last edited by sjalle; 07-16-2006 at 08:14 PM.
    eschew obfuscation

  6. #6
    Join Date
    May 2006
    Posts
    12
    So basically, if I was creating a chat style program, as I am, extending the JFrame to the ChatOne class is a very correct way to approach the problem?

    I'm basically trying to figure out how to approach the design of my classes so that they are designed in the OOP way and also so that in the future I can easily add functionality to the program if I wanted to.
    i.e. I used two panels in the ChatOne class in order to leave room for being able to handle all the contents of that JPanel in the future, say, by drag-and-drop to a new location w/in the chat client.

    The basic idea I have is to create the following classes:

    --Client class
    --Server class
    --Gui class (ChatOne)
    --any event handling class(es)

    Is this a resonable idea? Can you think of a better design approach?
    I guess I'm trying to learn how to program better.
    That is, I could create a chat program that was sloppy but performed all the functionality I needed. But, among other things, that could of course create problems in the future if changes were to be made.

    Thanks, thanks, thanks again!

  7. #7
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    All right, lets see...

    Server class: obviously a servlet with a database or filing system in the back, that handles a specific set of message types (response_message, new_message, change_message etc.). I would have used serialization for the client/server communication.

    Client class: I would have made the chat program as a downloadable MDI application (jar), that could spawn new chat panels inside it. Reason: You mention d&d and as I recall that is not a piece of cake for applets.
    This application would use a http communicator class (see attachment), and a class for the chat "panel" (it would be an extension of JInternalFrame).

    Then the GUIs and the Events.... I am quite pragmatic when it comes to solving problems and I think that a die hard belief in one method of solving all problems is countercreative.
    I usually handle events by making the class that is going to handle these an eventlistener for the specific events. I think it makes for cleaner code that is easy to read (anonymous inner classes are almost as messy as C++ code...) And if the processing can be coded in a page or two on my computer screen I keep that code inside the same class as the GUI. This is probably not the case for your chat program.
    You may want to keep the eventhandling inside the GUI and encapsulate the chat processing inside a separate class. Depending on your servers backbone (the DB/filesystem) this class could be a single application-wide instance or separate instances, one for each active chat-innerframe.

    Many ways to skin the cat, I could go on forever on this topic but this will have to do. You already have a good understanding of the importance of modularity and maintainability, so I wish you good luck.

    BTW, I have a pre-beta (haha) version of a chat program that does most of this, but I won't post it here unless you think it would be useful for you at this stage.
    Attached Files Attached Files
    eschew obfuscation

Similar Threads

  1. Comparison methods
    By ericelysia1 in forum Java
    Replies: 34
    Last Post: 05-15-2005, 06:39 PM
  2. Replies: 0
    Last Post: 05-27-2003, 11:12 AM
  3. Top fixed screen
    By Cheng in forum Web
    Replies: 1
    Last Post: 11-06-2001, 09:43 AM
  4. Static methods question
    By David Rancour in forum Java
    Replies: 1
    Last Post: 05-11-2001, 09:32 AM
  5. private and static
    By Mark in forum Java
    Replies: 3
    Last Post: 06-09-2000, 08:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center