Constructor accepting another class object

I have two classes. One is Address class and other is AddressBookEntry class
I havebeen asked to code a constructor in AddressBookEntry class that accepts name and the Address object. Can anyone tell what I've coded is correct or not(last part of the code)?
public class Address{
     private String street;
     private String city;
     private String state;
     private String zipcode;
     public Address(String addressStreet, String addressCity,
          String addressState, String addressZipcode){
          street = addressStreet;
          city = addressCity;
          state = addressState;
          zipcode = addressZipcode;
     } // end constructor
     public String getStreet(){ return street;}
     public String getCity(){ return city;}
     public String getState(){ return state;}
     public String getZipcode(){ return zipcode;}
     public String toString() {
     String addressObject = street+ "," + city + "," + state + "," +zipcode;
     return addressObject;
public class AddressBookEntry{
     private String name;
     private Address address;
     public static int entriesCount = 0;
     public AddressBookEntry(String entryName,Address addressObject){
          name = bookEntryName; // constructor in the AddessBookEntry class
          address = addressObject;

Still I have pblm with my assignment. I have modified my code
Address class
public class Address{
     private String street;
     private String city;
     private String state;
     private String zipcode;
     public Address(String addressStreet, String addressCity,
          String addressState, String addressZipcode){
          street = addressStreet;
          city = addressCity;
          state = addressState;
          zipcode = addressZipcode;
     } // end constructor
     public String getStreet(){ return street;}
     public String getCity(){ return city;}
     public String getState(){ return state;}
     public String getZipcode(){ return zipcode;}
     public String toString() {
     String addressObject = street+ "," + city + "," + state + "," +zipcode;
     return addressObject;
}b]AddressBookEntry
public class AddressBookEntry{
     private String name;
     private Address address;
     public static int entriesCount = 0;
     public AddressBookEntry(String entryName,Address addressObject){
          name = entryName;
          address = addressObject;
     public AddressBookEntry(String entryName, String entryStreet,     String entryCity,
                                   String entryState, String entryZipcode){
          name = entryName;
          address.street = entryStreet;
          address.city = entryCity;
          address.state = entryState;
          address.zipcode= entryZipcode;
          entriesCount++;
     public void setName(String entryName){
          name = entryName;
     public void setStreet(String entryStreet){
          address.street = entryStreet;
     public void setCity(String entryCity){
         address.city = entryCity;
     public void setState(String entryState){
          address.state = entryState;
     public void setZipcode(String entryZipcode){
          address.zipcode = entryZipcode;
     public String getAddress(String entryName){
          return address.toString();
     public String getName(){
          return name;
     public String toString(){
          String addressString = address.getStreet() + "\n"
                                             + address.getCity() + "\n"
                                           + address.getState() + "\n"
                                           + address.getZipcode() +"\n";
          return addressString;
     public static int getEntriesCount(){ return entriesCount;}
Driver Class
import javax.swing.*;
public class AddressBookApp{
public static void main (String args[]){
     String choice = "";
     while(!(choice.equalsIgnoreCase("x"))){
          String name = JOptionPane.showInputDialog("Enter name : ");
          String streetAddress = JOptionPane.showInputDialog("Enter street address : ");
          String city = JOptionPane.showInputDialog("Enter city : ");
          String state = JOptionPane.showInputDialog("Enter state : ");
          String zipcode = JOptionPane.showInputDialog("Enter zipcode : ");
          AddressBookEntry bookEntry = AddressBookEntry(name,street,city,
                                                  state,zipcode);
          String message = "Name : " bookEntry.getName() "\n"
               + "Address : \n"+bookEntry.toString();+ "\n"
          +"Press Enter to continue or 'x' to exit.";
          choice = JOptionPane.showInputDialog(message);
System.exit(0);
}

Similar Messages

  • Call a method of a class in a constructor of another class?

    Is this good programming or should i do it in another way?
    Consider an ordering system, where I have three classes, "Booking", "Table" and "Customer.
    My idea is to create a booking assigned to a table and a customer, the fields in the booking class is a Customer and a Table and the constructor assigns values to these field.
    In my Table class i have a method that books the table "bookTable(Customer customer)" and sets the availablility to 'false'.
    So my question is, is it good programming to call the method 'bookTable()' in the table class from the constructor of the Booking class? Or should i do it in another way?
    Edited by: DJHingapus on Jul 6, 2009 5:12 AM

    This sounds the wrong way around. What is the return value of bookTable(Customer)?
    I'd expect it to return a Booking object that it creates.
    Generally, you want the constructor to do as little as possible (while still only ever returning in a valid state, of course!).
    The problem you can get when you call other methods is that you introduce the possibility of other objects getting access to your object before the constructor has finished running (i.e. before the object is completely initialized). This can lead to nasty problems that are hard to find and debug.

  • Referencing a method in one class from a constructor in another?

    Hi,
    I'm not sure whether this is a simple question or not, but instead of rewriting the method in another class, is there a way that I can reference that method, eg:
    public int getTitleCode() {
            return titleCode;  }within the constructor of another class. I don't want to use inheritance with this because it would change all my existing contructors.
    Any ideas how to do this, or is it just simpler to add the method to both classes?
    Many thanks!

    Hi,
    I'm trying to use a method, defined in Class A, within one of the constructors in Class B. Class B object represents a copy of the output of Class A, with the addition of a few extra methods.
    Therefore to represent the details correctly in the saved text file for class B, I need to call a method from class A to save the text file for class B correctly.
    Class B saves a file with a reference number unique to that class, plus a reference number that is also saved in the text file for class A.
    I can achieve the correct result for the above by having the same method in both classes, but I just wondered whether instead of this I could in fact call the method from class A in the constructor for class B. With the following code,
        referenceNumber = refNum;
            titleReferenceNumber = titleRefNum;
            titleRefNum = titles.getTitleCode();
        }I just get a 'nullpointerexception' when I try to run this in the main class.
    Any help or advice appreciated!

  • Classes/Objects

    Hi,
    I have a class(Class A) that creates an object(HSSFSheet sheet), then passes this object over to the constructor of another class(Class B), Class B then changes some properties of [sheet] using its methods and then disposes itself, when Class A reads the properties of the [sheet] object they have not changed since it was first created, can anyone tell me why?

    Seems impossible
    Hi,
    I have a class(Class A) that creates an
    object(HSSFSheet sheet), then passes this object over
    to the constructor of another class(Class B), Class B
    then changes some properties of [sheet] using its
    methods and then disposesWhat do you mean with dispose?
    Can you post the java codes?
    Riccardo

  • Invoked super class constructor means create an object of it?

    Hei,
    i have create one class that extends another class. when i am creating an object of sub class it invoked the constructor of the super class. thats okay.
    but my question is :
    constructor is invoked when class is intitiated means when we create an
    object of sub class it automatically create an object of super class. so means every time it create super class object.

    Hi,
       An object has the fields of its own class plus all fields of its parent class, grandparent class, all the way up to the root class Object. It's necessary to initialize all fields, therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly.
       The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor.
    Normally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
       1. You want to call a parent constructor which has parameters (the automatically generated super constructor call has no parameters).
       2. There is no parameterless parent constructor because only constructors with parameters are defined in the parent class.
       I hope your query is resolved. If not please let me know.
    Thanks & Regards,
    Charan.

  • How to add objects to panel in one class from another class

    Hi this is what i am trying to do. I have a drag and adrop tool working where the users and select objects on a small panel and drag them to another panel called the tpan. What i want to do is create another class, which creates objects and now i want to display these objects on the tpan. So say i have a class DisplayTpan(), this class is used to display the objects which have been dragged from the small panel, and objects on this panel have mouselisteners attached, so that these objects can be moved around on the tpan. I have created another class called creatObj(), and from this class i want to add objects to the tpan. The DisplayTpan class extends a Jpanel, would this be he case for the CreateObj() class? In the CreateClass i have made a call to DisplayTpan t = new DisplayTPan();
    t.add(object);
    But this does not add the object to the panel, any ideas on how it should be done?
    Problem number two i have is say, I have two objects created on that oanel, i now want to draw a line t connect the two objects, this is just simply a call to the drawLine function but how would it be possible to add a ,mouselistener to that line, so it can be extended moved around etc? Any help much appreciated thanks.

    Try to convert the PL/SQL code from Forms trigger into a PL/SQL library(.PLL),
    and then attach that PLL in your forms.
    Note that all Forms objects should be referenced indirectly, for example,
    you have to rewrite
    :B1.DEPT_CODE := :B2.DEPT_CODE;
    :B3.TOTAL_AMOUNT := 100;
    ==>
    copy('B2.DEPT_NO','B1.DEPT_NO');
    copy('100','B3.TOTAL_AMOUNT');
    This is the best way to share PL/SQL code among Oracle Forms.

  • How to add objects to panel from another class?

    Hi this is what i am trying to do. I have a drag and adrop tool working where the users and select objects on a small panel and drag them to another panel called the tpan. What i want to do is create another class, which creates objects and now i want to display these objects on the tpan. So say i have a class DisplayTpan(), this class is used to display the objects which have been dragged from the small panel, and objects on this panel have mouselisteners attached, so that these objects can be moved around on the tpan. I have created another class called creatObj(), and from this class i want to add objects to the tpan. The DisplayTpan class extends a Jpanel, would this be he case for the CreateObj() class? In the CreateClass i have made a call to DisplayTpan t = new DisplayTPan();
    t.add(object);
    But this does not add the object to the panel, any ideas on how it should be done?
    Problem number two i have is say, I have two objects created on that oanel, i now want to draw a line t connect the two objects, this is just simply a call to the drawLine function but how would it be possible to add a ,mouselistener to that line, so it can be extended moved around etc? Any help much appreciated thanks.

    As for your first problem...too confusing...too tired...mb tomorrow it will make sense :)
    Fer the second...no need to add a mouse listener to each line. There are a couple options that spring to mind, the easiest I can think of is just check to see if the mouse click intersects with any of the lines (bit of geometry).
    The second, ugly but a hella allot more accurate and better (me thinks), is to create a bounding box around the line, so the user doesn't have to click right right on the line. I created this bounding box by painting the pixels with a special key to correspond to that line. The other nice thing about this key is the fact that the lookup is quick.
    The first step was the create a array of integers the size of the surface. Whenever a line is drawn on the graphical surface, do a corresponding line in the integer array, and create the bounding box inside this invisible array. Now whenever the user clicks just do a lookup into this array and check to see which line was selected...then go to town.
    If you want a more detailed explination, i'll post some code later.

  • Changing an object by calling a method in another class that returns nothin

    How can a method like for example Arrays.sort(Object[] a) work? The method has a return statement void, so how come the array passed into the method "magically" end up as being sorted when we look at it in another class after having called this method?

    jverd wrote:
    sunfun99 wrote:
    Since references really are more like addresses, jverd's adress-on-pieces-of-paper analogy is the best, but certainly not because the addresses on the pieces of paper are copies of the address (they aren't). We may just be splitting ever finer semantic hairs here, but how is it not a copy of the address?It is a finely split hair - and ultimately just a difference of language use, I think.
    We scribble on pieces of paper and thereby have at least two things to deal with: the scribble, and the location. It is unfortunate, but in English both things are referred to as "the address". The scribble has qualities like "red", "legible" etc, the location has qualities like "distant", "next door to the president": so they do seem to be different things.
    We use "address" for both: "I can't read this address" vs "Go to this address". Children make jokes based on the ambiguity: "How do you spell it."
    But then there's a third thing: the denotation of the location by the scribble. (denotation here == reference/pointing-at/leash/stick etc). It really does seem to be a third thing. (With apologies to Jean Buridan) consider a person who has lat/long coordinates explained to them for the first time and is handed a piece of paper with coordinates on it. They are asked "Do you know who lives here?" and they answer "Yes, I know the person at this address!". Most would say the statement is false - even if it turns out they were handed their own address. Their assertion of knowledge is an assertion about the denotation of the location by the coordinates, not about the location itself.
    So what is copied by a scribe or a photocopy machine when it copies an address? Clearly it's the scribble, not the location. The scribble is duplicated, the location is not. But what about the denotation of the location by the scribble? Not withstanding the above example (and especially in contexts where knowledge and similar concepts are not involved), you could say that the denotation of the location by the scribble is a value. In other words you could hold that two denotations of some location are not just equal but identical iff they denote the same location. (You could, but you needn't.) It is in this sense that the pieces of paper bear, not copies of the address, but the same address.
    (Exactly the same applies to "pointers" ie signposts. If you have two "north pole" signs (1) The are different signs (2) They point to the same place (3) They are two signs bearing one and the same reference.)
    Edited by: pbrockway2 on Mar 15, 2009 12:49 PM

  • Assigning object of one class to object of another class.

    Hi,
    How will i assign an object of one class to an object of another class?
    Ex:
    ClassX A=some_method();
    Now how will I assign the object A of class ClassX to the object 'B' of another class 'ClassY'.

    In java you can only assign a object reference of one class into object reference of another class if the first class is the Second class (in other words the first class is a subclass of second class).
    for example if this is a inheritance chart
    Car ==========>Mercedes
    "===========>Audi
    then you can use
    Audi a1 = new Audi();
    Car c1 = a1;
    or Mercedes m1 = new Mercedes();
    Car c1 = m1;
    but not
    a1 = m1;
    before assigning a variable into another variable of different class, use:
    if(variable1 instanceOf ToBeAssignedIn Class){
    variable2 = variable1;
    example:
    Audi a1;
    Car c1;
    if(a1 instanceOf Car){
    c1 = a1;
    Edited by: gaurav.suse on Apr 10, 2012 1:14 PM
    Edited by: gaurav.suse on Apr 10, 2012 1:15 PM

  • How to pass the object of one class to the another class?

    Hello All,
    My problem is i am sending the object of serializable class from one class to another class but when i collection this class into another it is transfering null to that side even i filled that object into the class before transfer and the point is class is serializable
    code is below like
    one class contain the code where i collecting the object by calling this function of another class:-
    class
    lastindex and initIndex is starting and ending range
    SentenceStatusImpl tempSS[] = new SentenceStatusImpl[lastIndex-initIndex ];
    tempSS[i++] = engineLocal.CallParser(SS[initIndex],g_strUserName,g_strlanguage,g_strDomain);
    another class containg code where we transfering the object:-
    class
    public SentenceStatusImpl CallParser(SentenceStatusImpl senStatus, String strUserName, String strLanguage, String strDomain)
    *//here some code in try block*
    finally
    System.+out+.println("inside finally...........block......"+strfinaloutput.length);
    senStatus.setOutputSen(strfinaloutput);//strfinaloutput is stringbuffer array containg sentence
    fillSynonymMap(senStatus);
    senStatus.setTranslateStatus(*true*);
    return senStatus;
    Class of which object is serialized name sentenceStatusimpl class:-
    public class SentenceStatusImpl implements Serializable
    ///Added by pavan on 10/06/2008
    int strSourceSenNo;
    String strSourceSen = new String();
    String strTargetSen = new String();
    StringBuffer[] stroutputSen = null;
    HashMap senHashMap = new HashMap();
    HashMap dfaMarkedMap = new HashMap();
    boolean bTargetStatus = false;
    public SentenceStatusImpl(){
    public void setOutputSen(StringBuffer[] outputSen){
    stroutputSen = outputSen;
    public StringBuffer[] getOutputSen(){
    return stroutputSen;
    public void setTranslateStatus(*boolean* TargetStatus){
    bTargetStatus = TargetStatus;
    }//class

    ok,
    in class one
    we are calling one function (name callParser(object of sentenceStatusImpl class,.....argument.) it return object of sentenceStatusImple class containg some extra information ) and we collecting that object into same type of object.
    and that sentenceStatusImple classs implements by Serializable
    so it some cases it is returning null
    if you think it is not proper serialization is please replay me and suggest proper serialization so that my work is to be done properly (without NULL)
    hope you understand my problem

  • Instantiate a Class through a constructor argument of another class.

    public function LevelManager(owner:Home)
                                  _owner = owner;
    In my LevelManager Class I have the above code in the constructor. Home is another Class which is not instantiated anywhere with the new keyword. It is merely a parameter in the constructor and then passed into the body and assigned to a local variable. I didn't know you could instantiate a class through a function parameter. Is that right???
    Cheers in advance.

    Well, I know Amy is big on design patterns and she is going to slap me but I am the guy who is not a big fun of DPs in regular Flash applications. I have many reasons to dislike them.
    I am not against DPs in principal. In collaborative environments (big teams) or in situations when software is developed for industrial consumption or as partially closed frameworks - it makes sense. Otherwise - they are just possible solutions and reference point at best. In Flash they frequently are major silly overkills. They are more of academic than practical value contrary to what people tend to believe.
    Design patterns are possible solutions that developers came up with heuristically base on the problems they needed to solve - not vice versa. Problems do not dictate design patterns.
    There is a strong tendency among DPs proponents and followers to make DPs self-fulfilling prophecies. Instead of conceptualizing of particular application needs developers often are searching for DP first and then try to squeeze logic into a particular or a group of several design patterns.
    If a person is taught that DPs is the only way to go - there is a great danger of killing creativity and the thought process.
    I strongly believe that what makes a star programmer is the ability to conceptualize the project, model it well and only then find coding solutions based on language capacities. And to question any suggestions in favor of current task efficiencies.
    By the same token, if your painting doesn't need color red - why use it? This is another thing that happens often - developers implement something that is actually not needed.
    Code is cheap! When project is well conceived and modeled - coding takes very little time. One ends up with his/her own "design pattern" that may or may not fall into one of DPs that is articulated already.
    Also, there is a great deal of activism around DPs that, as with any activism, forms an ideology that is full of misleading simplifications.
    First one is that OOP is equated to DPs usage. This is totally dangerously  untrue!!!
    Another one is you mentioned. Spaghetti coding is not the only alternative to design patterns. In other words, if one doesn't use DP - it absolutely doesn't mean person is engaged in spaghetti coding. And vice versa - DP does not shield program from spaghetti coding. I have seen DP warriors going crazy with spaghetti coding although DP was implemented to the tee.
    Another example of misconception is that DP proponents always carry banners of decoupling and modularization. Be very skeptical when someone gives you this shpeal. Modularization is easy to conceal for "propaganda" purposes and it is comfortable not to think about when DPs are used (especially MVC concept). Since this is just a concept - there are no real checks and balances.
    Decoupling, on the other hand, is not that easy to shove down someone's throat. Decoupling can be actually calculated - this is where a lot of idealistic beliefs that someone's code is well decoupled because of the DP fails miserably. Not because of DP itself but because of implementation. Well, sometimes pattern too.
    See, there is no black and white again.
    My point is that DPs do not protect anyone from any kind of challenges or mistakes as they don't make a better programmer. They can make one a disciplined follower but not a real creator (not that everyone must be the Creator).
    If not used properly DPs may be a ground for crappy inefficient un-scalable application as much as any other approach.
    And the last thing. I said that DPs are special suspects in Flash. This is because ActionScript and Flash are already limited frameworks that force us into thinking in MVC terms. This is just a nature of the beast. To attempt to warp it up into another MVC framework looks like a self-indulgent irrelevant academic activity to me.
    And I did not even mentioned practicalities of the target environments we develop our applications for.

  • ABAP Objects : calling one method from another class

    Hi,
    Can you please tell me how to call method from one class or interfce to another class.The scenario is
    I have one class CL_WORKFLOW_TASK, this class have interface IF_WORKFLOW_TASK & this interface have method IF_WORKFLOW_TASK~CLOSE. Now my requirement is ,
    There is another class CL_WORKFLOW_CHAIN ,this class have interface IF_WORKFLOW_CHAIN & this interface have method IF_WORKFLOW_CHAINCLOSE_ALL_PREDECESSORS. Now i have to write my code in this method but i have to use IF_WORKFLOW_TASKCLOSE method for closing the task.
    Can you please give me the code for the above .
    Please waiting for reply.

    Hi,
    You can use the concept of INHERITANCE  in this scenario.By using this concept, you can call all the public and protected  methods of class CL_WORKFLOW_TASK  in the required calss CL_WORKFLOW_CHAIN as per your requirement.
    Go through the  Introdctory(INHERITANCE) programming from this SAPHELP link.
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    I hope, it will help in you inresolving your problem.
    by
    Prasad GVK.

  • How to pass params to another class which accepts keyboard input?

    How can I pass params to a stand-alone Java class that, when executed, gathers params using readLine()?
    In other words, MyClass, when executed from the command-line, uses readLine to gather params for program execution. I'd like to test this class by calling it from another class using Runtime.exec("java MyClass") or calling MyClass.main(args) directly. But, how can I simulate the input expected from the keyboard?
    Thanks!

    Alright, so it looks like this:
    proc = Runtime.getRuntime().exec("java Client");
    br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
    bw.write("test");
    bw.newLine();
    But, how can write doesn't seem to be passed to the original client class.
    Suggestions?

  • How can I to control any element of my GUI from another class?

    How can I to control any element of my GUI from another class?

    For that, you need the external class to have the reference to your element.. If your idea is to change basic properties like width, height etc.. then you can have the constructor of the external class to take the object of the parent of your class as the parameter and modify ..
    However, if the properties to be altered/accessed are custom to your element, then you will have to have the class accept an object of your class as the parameter. No other option..
    What exactly is your requirement?

  • Stop a method from executing until another class does its bit

    Hi all,
    For my app I have a login screen where to get login success the user must first register. I therefore have two class LoginDialog and Register which is a dialog.
    In LoginDialog if the user clicks on Register it brings up a new instance of the Register dialog but continues to process the calling method (which happens to return to another class processing the login). What I require is that when I create a new Register object, the creating method does nothing until the Registration form is completed. I'm not at all au fait with threads so was wondering if there is an easy way to do it.
    I have thought of passing the LoginDialog as an argument in the Register constructor and having an empty while loop running in the invoking method (i.e. while (false) do nothing) and creating public access to that boolean variable so that at completion of the registration it sets the boolean variable to true in LoginDialog so it should break out of the while loop and continue. Is that a satisfactory way of pausing and restarting a method?
    Cheers,
    Chris

    Hi,
    I have a MainFrame class which calls processLogin which creates a new LoginDialog which houses the Register button. When I click on the register button it opens a new Registration screen but LoginDialog returns to MainFrame in the background and says that no user has logged in. What I require is that when the Register object is created after clicking the Register button that LoginDialog waits until the Registration is complete.
    Maybie the code will help (sorry if it is a bit lengthy).
    Snippet of LoginDialog
    public void actionPerformed(ActionEvent event)
            if(event.getSource() == ok) {
                 _username = user.getText();
                   _password = new String(password.getPassword());
                   _server = server.getText();
                   //ensure port number is an integer
                   try{
                        _port = Integer.parseInt(port.getText());
                   catch(NumberFormatException e){
                        JOptionPane.showMessageDialog(this,
                        "Please use an integer value only for the port number","Error",
                        JOptionPane.WARNING_MESSAGE);
                   //checks username and password length
                   if((_username.length()==0) || (_password.length() == 0)){
                        JOptionPane.showMessageDialog(this,
                             "Please enter a valid username and password","Error",
                                  JOptionPane.WARNING_MESSAGE);
                        return;
                   //checks server length
                   if(_server.length()== 0){
                        JOptionPane.showMessageDialog(this,
                             "Invalid server host","Error",
                                  JOptionPane.WARNING_MESSAGE);
                        return;
                   try{
                        db = new DatabaseConnection();
                        boolean exists = db.doesUserExist(_username, _password);
                        db.close();
                        if(exists){
                             //System.out.println("User exists on database");
                             this.dispose(); //get rid of login screen now user is confirmed
                        if(!exists){
                                  _username = null;
                                  _password = null;
                                  this.dispose();
                   catch(java.sql.SQLException e){
                        JOptionPane.showMessageDialog(this,
                             "Unable to connect to database. Please try again.","Error",
                                  JOptionPane.WARNING_MESSAGE);
              else if(event.getSource() == cancel) {
                   //NOTHING
              else if(event.getSource() == register){
                   Register register = new Register();
                   //while (processRegistration){
              this.setVisible(false);
         }and Register
    //import classes
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JFrame implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFirstName;
         JLabel lblLastName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblEmail;
         JLabel lblSex;
         String userName;
         char[] userPwd;
         char[] cnfPwd;
         String strUserPwd;
         String strCnfUserPwd;
         String firstName;
         String lastName;
         String age;
         String empid;
         String email;
         String sexStr;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox comboSex;
         JTextField txtUserName;
         JPasswordField txtUserPwd;
         JPasswordField txtCnfUserPwd;
         JTextField txtFirstName;
         JTextField txtLastName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         DatabaseConnection db;
         boolean exists, entrySuccess;
         public Register() {
              this.setTitle("Register");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Registration Info");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUserPwd = new JPasswordField(15);
              panel.add(txtUserPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUserPwd=new JPasswordField(15);
              panel.add(txtCnfUserPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFirstName=new JLabel("First Name");
              panel.add(lblFirstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFirstName=new JTextField(15);
              panel.add(txtFirstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLastName=new JLabel("Last Name");
              panel.add(lblLastName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLastName=new JTextField(15);
              panel.add(txtLastName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sexArr = {"Male", "Female"};
              comboSex = new JComboBox(sexArr);
              comboSex.setSelectedIndex(0);
              panel.add(comboSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setVisible(true);
              setSize(450,400);
         }//end or Register()
         public void actionPerformed(ActionEvent ae) {
              Object o = ae.getSource(); //get the source of the event
              if(o == btnCancel)
                   this.dispose();
              if(o == btnSubmit){
                   userName = txtUserName.getText();
                   userPwd = txtUserPwd.getPassword();
                   strUserPwd = new String(userPwd);
                   cnfPwd = txtCnfUserPwd.getPassword();
                   strCnfUserPwd = new String(cnfPwd);
                   firstName = txtFirstName.getText();
                   lastName = txtLastName.getText();
                   age = txtAge.getText();
                   empid = txtEmpId.getText();
                   email = txtEmail.getText();
                   sexStr = (String)comboSex.getItemAt(0);
                   db = new DatabaseConnection();
                   //Now check to see if username and password combination have been
                   //taken
                   try{
                        exists = db.doesUserExist(userName.trim(), strUserPwd.trim());
                   catch (java.sql.SQLException e){
                        System.out.println(e);
                   //Checks that each field has been filled in.
                   if(userName.length() == 0 ||  strUserPwd.length() == 0 ||
                   strCnfUserPwd.length() == 0 || firstName.length() == 0 ||
                   lastName.length() == 0 || age.length() == 0 || empid.length() == 0
                   || email.length() == 0){
                        JOptionPane.showMessageDialog(this,
                        "One or more entry has not been filled in. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);     
                   //Ensures that passwords match
                   if(!strUserPwd.equals(strCnfUserPwd)){
                        JOptionPane.showMessageDialog(this,
                        "Passwords do not match. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);
                   if(exists){
                        JOptionPane.showMessageDialog(this,
                        "Username and password combination already exists. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);
                   if(!exists) {
                        String userDetails = (userName.trim() + " " + strUserPwd.trim()
                        + " "  + firstName.trim() + " "
                        + lastName.trim() + " " + age.trim() + " " + empid.trim() + " "
                        + email.trim() + " " + sexStr.trim());
                        //System.out.println(userDetails);
                        //Try to connect to the database and insert the user details.
                        //If successful then user will be alerted and the registration page
                        //should be disposed automatically. If for some reason the insert
                        //was not successful then user is prompted to try again.
                        try{
                             entrySuccess = db.registerUser(userDetails);
                             if(entrySuccess){
                                  JOptionPane.showMessageDialog(this,
                                  "Congratulations, you have successfully registered for the Instant Messenger service!",
                                  "Message", JOptionPane.INFORMATION_MESSAGE);
                                  this.dispose();     
                             if(!entrySuccess){
                                  JOptionPane.showMessageDialog(this,
                                  "There was a problem entering your details. Please try again.",
                                  "Message", JOptionPane.ERROR_MESSAGE);
                        catch(java.sql.SQLException e){
              }//end of else
              db.close();
         }//end of actionPerformed()
    }//end of classCheers,
    Chris

Maybe you are looking for