Link to home
Start Free TrialLog in
Avatar of Bekkerus
Bekkerus

asked on

Using Objects

Hello,

 Still trying to learn Java. OK, I have two JPanels trying to use the same "Contract" Object and I am having some problems. I created the public instance of the Contract in one JPanel then I try and call a method from the Contract object from a seperate JPanel. This does not work, it says "non-static variable conInfo cannot be referenced from a static context".

 That is not good because if the object is static then I have only one instance of it for everyone who uses these form. I believe that 10 people will be using this so each one needs to have a seperate Contract object.

 Basically I have a tabpanel and as the user moves from the first panel to the second panel I want to display the data from "Contract" object in the next tab. What can I do to make this work right?

public class ContractTab extends javax.swing.JPanel
{
     public ContractInfo conInfo;
.
.
.
     
     private void btnInsertRowActionPerformed(java.awt.event.ActionEvent evt)
     {
          String cid = tfCompanyID.getText();
             conInfo = new ContractInfo(cid);
     }
}

public class MarginTab extends javax.swing.JPanel
{
.
.
.
//-----Get Company Name and set value into a text field of different form
     String c ="";
     c = ContractTab.conInfo.getCompanyName();
     tfProductOwner.setText(""+c);  
     tfProductOwner.setBounds(140, 25, 120, 20);

}


public class ContractInfo
{
     private String companyName;
     private int companyID;
     private String beginDate;
     private String endDate;

     /** Default Empty Constructor */
     public ContractInfo()
     {
          companyName = "";
          companyID   = 0;
          beginDate   = "";
          endDate     = "";
     }

     public ContractInfo(String cn)
     {
          companyName = cn;
     }    
     
     public ContractInfo(String cn, int cid, String bday, String eday)
     {
          companyName = cn;
          companyID   = cid;
          beginDate   = bday;
          endDate     = eday;
     }

     //Get the currect object
     public ContractInfo getContract()
     {
          return this;
     }

     public String getCompanyName()
     {
          return companyName;
     }

     public int getCompanyID()
     {
          return companyID;
     }

     public String getBeginDate()
     {
          return beginDate;
     }

     public String getEndDate(String eday)
     {
          return endDate;
     }    

     public void setContractName(String cn)
     {
          companyName = cn;
     }

     public void setContractID(int cid)
     {
          companyID = cid;
     }

     public void setBeginDate(String bday)
     {
          beginDate = bday;
     }

     public void setEndDate(String eday)
     {
          endDate = eday;
     }
}

Thanks,
mark
Avatar of Mick Barry
Mick Barry
Flag of Australia image

conInfo is not static, in fact that is what the error is complaining about ie. that it isn't static.

The following line is attempting to access conInfo as a static variable as you are not supplying it with a ContractTab instance.

c = ContractTab.conInfo.getCompanyName();

You instead need an instance of a ContractTab object to be able to access the conInfo object.

ContractTab tab = .........;
c = tab.conInfo.getCompanyName();
Avatar of Bekkerus
Bekkerus

ASKER

Objects,

 I am pretty confused. I made this ContractInfo object so that I could save info into it then on seperate pages I would be able to reference it. But it appears I have to make seperate instances of it in each form but then I lose the ability to use the same data between forms. If I use a static which I am NOT, then I would only get one ContractInfo object for all users logged on. That would be BAD. Since they all want to make seperate contracts.

 I do not know what to do.

-mark
Currently every instance of a ContractTab object includes an instance of a ContractInfo object.
For another object (ie. MarginTab instance) to be able to access this ContractInfo instance it needs a reference to the ContractInfo objects itself, or a reference to the ContractTab object.
Objects,

 Option 1) OK, so how do I reference the ContractInfo object itself within the MarginTab class?

 Option 2) To reference to the ContractTab object would I then have to use a static ContractInfo?

 Examples would be awesome!!! Hopefully tomorrow I can make this work that be wonderful. Thanks.

-mark
class A
{
   public C stuff;

   ....
}

class B
{
   // Keep a reference to instance of A
   A ref;

   public B(A a)
   {
      // Store reference to instance of A in ctor
      ref = a;
   }

   void fn()
   {
     C c = ref.stuff;
   }
}

class C
{
   ...
}
Objects,

 Does this look correct according to your ABC model into my current situation?

public class ContractTab extends javax.swing.JPanel
{
    public ContractInfo conInfo;
.
.
.
.
    private void btnInsertRowActionPerformed(java.awt.event.ActionEvent evt)
    {
     String cid = tfCompanyID.getText();
            conInfo = new ContractInfo(cid);
    }
}

public class MarginTab extends javax.swing.JPanel
{
    private ContractTab ctab;  //create a reference of ContractTab
.
.
.
.
    public MarginTab(ContractTab myref)
    {
     ctab = myref;
    }

    public void getName()
    {
     //-----Get Company Name and set value into a text field of form

     String c ="";
     ContractInfo acopy = ctab;
     c = acopy.getCompanyName();
     tfProductOwner.setText(""+c);  
     tfProductOwner.setBounds(140, 25, 120, 20);
}


public class ContractInfo
{
.
.//my contractInfo Object
.
.
}
Yes that looks fine, though you don't need acopy in the following:

ContractInfo acopy = ctab;
c = acopy.getCompanyName();

You can simply do:

c = ctab.getCompanyName();
objects,

 Shoot, I am still having problems I will try and descripe the problem tomorrow. I will use a new example because I might have over simplified my problem. I still have no idea how or where to create the objects so that the information can be shared correctly. objects is it ok to send an email with code in it?
that's fine.
Object,

 Here is an updated situation. I have a form that a user does a search for matching products. when they click search a new form opens showing the matches. the form has a jlistbox when they select an item and click select. the form passes a object list into a data object "prdData".

 The orginal form that called the search has a jTextArea this should be populated from the prdData dataObject after the search form closes. The updating is not working. I thought about using a Thread to listen for when the search frm closes but that has not worked? How can I update the TextArea?

 Since I changed the question I am going to post it up in a new question. But I will leave this open for you to look at if you like.


import javax.swing.*;
import javax.swing.table.*;
import java.sql.DriverManager;
import java.sql.*;
import java.util.*;
import java.awt.event.*;

public class MarginTab extends javax.swing.JFrame {
   
    //Instance Variables

    SearchResult Sframe;
    UpdateAfterSearchThread at = new UpdateAfterSearchThread();

    private javax.swing.JPanel pSearch;
    private javax.swing.JLabel lblProductSearch;
    private javax.swing.JTextField tfSearch;
    private javax.swing.JButton btnSearch;
    private javax.swing.JPanel pMargin;
    private javax.swing.JScrollPane spProduct;
    private javax.swing.JTextArea taProductList;


    /** Creates new form MarginTab */
      public MarginTab()
      {
            initComponents();
      }
   
    /** This method is called from within the constructor to
     * initialize the form.
     */
     
    private void initComponents() {
        pSearch = new javax.swing.JPanel();
        lblProductSearch = new javax.swing.JLabel();
        tfSearch = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        spProduct = new javax.swing.JScrollPane();
        taProductList = new javax.swing.JTextArea();


        getContentPane().setLayout(null);

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        pSearch.setLayout(null);
       
        pSearch.setBorder(new javax.swing.border.LineBorder(java.awt.Color.black, 1, true));
        lblProductSearch.setText("Product Search..........");
        getContentPane().add(lblProductSearch);
        lblProductSearch.setBounds(10, 15, 120, 16);
       
        getContentPane().add(tfSearch);
        tfSearch.setBounds(130, 10, 140, 20);
       
        btnSearch.setText("Search");
        btnSearch.setMargin(new java.awt.Insets(2, 5, 2, 5));
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
       
        getContentPane().add(btnSearch);
        btnSearch.setBounds(275, 10, 65, 20);
       
        getContentPane().add(pSearch);
        pSearch.setBounds(10, 150, 350, 40);
        spProduct.setViewportView(taProductList);
       
        getContentPane().add(spProduct);
        spProduct.setBounds(10, 200, 350, 60);
   
    }
   
//PROBLEM :
//USER BEGINS A SEARCH CREATE SEARCH FORM
//START A THREAD
          private void btnSearchActionPerformed(java.awt.event.ActionEvent evt)
      {
            String x = tfSearch.getText();
            System.out.println(""+x);
            
            
            if (Sframe != null)
            {
                  Sframe.hide();
                  Sframe = null;
                  System.gc();
                  Sframe = new SearchResult(x);
                  Sframe.setBounds(70,100,380,130);
                  Sframe.setVisible(true);
                  at.start(); //<--------THREAD START
            }
            else
            {
                  Sframe = new SearchResult(x);
                  Sframe.setBounds(70,100,380,130);
                  Sframe.setVisible(true);
                  at.start(); //<--------THREAD START
            }
      }

//PROBLEM :
//WHEN THE SEARCH FORM CLOSES UPDATE THE TEXTAREA.
      class UpdateAfterSearchThread extends Thread
      {
            boolean open;
            public void run()
            {
                  open = Sframe.isShowing(); //test if search form is open

                    while(open)
                  {
                        try
                        {
                              sleep(10); // sleep time in milliseconds
                        }
                        catch (InterruptedException ex)
                        {
                              System.out.println("Thread failed..."+ex);
                        }
                  }
                  refreshList(); //<---while loop ended so refresh now?

            }
            
            // this adds the item id into the jTextArea
            // but never seems to get called.
            public void refreshList()
            {
                  String itemID ="";
                  Object list[] = ContractUI.prdData.getrl();
            
                  for(int i = 0; i < list.length; i++)
                  {      
                        itemID = (String) list[i];
                        itemID += ",";
                  }
            
                  taProductList.append(itemID);
                  taProductList.revalidate();
                  taProductList.repaint();
                  System.out.println("refreshList");
            }

            public void stopIt()
            {
                    open = false;
            }
      }

    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
            System.out.println("close contract form");
    }

      public static void main (String args[])
      {
            MarginTab frame = new MarginTab();
            frame.setBounds(150,150, 325,260);
            frame.setTitle("Main Menu");
            frame.setVisible(true);
      }
}




/*
 * SearchResult.java
 * Created on March 3, 2002, 10:26 PM
 */

//import java.sql.DriverManager;
//import java.sql.*;
import java.util.*;
 
public class SearchResult extends javax.swing.JFrame
{

      /** Creates new form SearchResult */
      public SearchResult(String product)
      {
            setProductList(product); //begin search for matching items
            initComponents();
      }
      
      /** This method initializes the form.
      */
      private void initComponents()
      {
            spProduct = new javax.swing.JScrollPane();
            lstProducts = new javax.swing.JList();
            Vector listData = new Vector();
            for (int i =0; i<productList.length; i++)
            {
                  //put the vector into the list
                  listData.addElement(productList[i][0]);
                  lstProducts.setListData(listData);
            }
            
      
            btnSelect = new javax.swing.JButton();
            btnCancel = new javax.swing.JButton();
       
            getContentPane().setLayout(null);
       
            setTitle("Search Results...");
            addWindowListener(new java.awt.event.WindowAdapter()
            {
                  public void windowClosing(java.awt.event.WindowEvent evt)
                  {
                        exitForm(evt);
                  }
            });
       
            spProduct.setViewportView(lstProducts);
       
            getContentPane().add(spProduct);
            spProduct.setBounds(10, 20, 260, 70);
       
            btnSelect.setText("Select");
            btnSelect.setMargin(new java.awt.Insets(2, 10, 2, 10));
            btnSelect.addActionListener(new java.awt.event.ActionListener()
            {
                  public void actionPerformed(java.awt.event.ActionEvent evt)
                  {
                        btnSelectActionPerformed(evt);
                  }
            });
       
            getContentPane().add(btnSelect);
            btnSelect.setBounds(290, 20, 70, 21);
       
            btnCancel.setText("Cancel");
            btnCancel.setMargin(new java.awt.Insets(2, 10, 2, 10));
            btnCancel.addActionListener(new java.awt.event.ActionListener()
            {
                  public void actionPerformed(java.awt.event.ActionEvent evt)
                  {
                        btnCancelActionPerformed(evt);
                  }
            });      
            getContentPane().add(btnCancel);
            btnCancel.setBounds(290, 50, 70, 21);
       
            pack();
      }
      
// Find matching items
// this works ok.
      public void setProductList(String prod)
      {
            /* commented out so it can run anywhere

            try
            {
                  try
                  {
                        DriverManager.registerDriver( (Driver)Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
                  }
                  catch(Exception e)
                  {
                        System.out.println(e);
                  }
                  
                  String url = "jdbc:oracle:thin:@www20.x.com:1559:com";
                  Connection con = DriverManager.getConnection(url, "SQ", "S9");
                  Statement stmt1 = con.createStatement();
                  Statement stmt2 = con.createStatement();
                  ResultSet rs1;
                  ResultSet rs2;

                  
                  int count = 0;
                  rs1 = stmt1.executeQuery("SELECT PRODUCT_DATA_ID, PRODUCT_NAME FROM TEMP_PRODUCT WHERE PRODUCT_NAME ='"+prod+"'" );
                  while(rs1.next())
                  {
                        count++;
                        //this is probably dumb to count results so i can size my array
                        //but it is the only way I know how to get the rs count.
                  }

                  //Create the arrays that holds the data
                  productList = new Object[count][1];
                  int rec = 0;
                  rs2 = stmt2.executeQuery("SELECT PRODUCT_DATA_ID, PRODUCT_NAME FROM TEMP_PRODUCT WHERE PRODUCT_NAME ='"+prod+"'" );
                  while(rs2.next())
                  {
                        productList[rec][0] = rs2.getString(2)+rs2.getInt(1);
                        rec++;
                  }
            }
            catch (Exception e)
            {
                  System.out.println("Failed to find matching products");
                  e.printStackTrace();
            }

            */
      }            
      
//this might be problem area//
      public void setResults()
      {
            //get the selected item into object array
            Object[] result = lstProducts.getSelectedValues(); //<---pop result from list object on form

            //update the public static prdData to new array.
            ContractUI.prdData.setrl(result); //<-- pass value into prdData object.

            //This seems to work but the updating
            //of the jTextArea is always a problem
            //because it is called from the MarginTab form
            //it never has access to update the control
            //in the other form.
      }

      private void btnSelectActionPerformed(java.awt.event.ActionEvent evt)
      {
            //USER SELECTS ITEM. UPDATE LIST
            setResults();
            this.hide();
         }

      private void btnCancelActionPerformed(java.awt.event.ActionEvent evt)
      {
            this.hide();
         }      
      
      /** Exit the Application */
      private void exitForm(java.awt.event.WindowEvent evt)
      {
            this.hide();
      }
      

      private String productName;         
      //User entered search parameter
      
      private Object[][] productList;
      //complete list of all the product names, from DB, that matches the user search
      
      private Object[][] returnL = new Object[50][1];            
      //this is the list they actually want to add to the jTextArea on the marginTab form
      

      private javax.swing.JScrollPane spProduct;
      private javax.swing.JList lstProducts;
      private javax.swing.JButton btnSelect;
      private javax.swing.JButton btnCancel;        
}

No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- To be PAQ'ed and points refunded

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
ASKER CERTIFIED SOLUTION
Avatar of Chmod
Chmod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial