Static Function problem

Hi, I have been recently working on a program and have come across this error that has stumped me!
prefsPane.java:101: non-static method updateVar(int) cannot be referenced from a static context
divLetter = divPane.updateVar(0);
^
prefsPane.java:102: non-static method updateVar(int) cannot be referenced from a static context
divName = divPane.updateVar(1);
^
// divPane.java Creates a new divPane. DuH!
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class divPane extends JPanel {
protected JLabel letterLabel, nameLabel;
protected JButton applyButton;
String newLetter, newName;
public JTextField letterField, nameField;
     public divPane(String divName, String divLetter) {
          super(new GridBagLayout() );
          // Initalize the JLabels
          letterLabel = new JLabel("Id for Letters: ");
          nameLabel   = new JLabel("Id for Names: ");
          // Initalize the JTextField
          letterField = new JTextField(divLetter, 10);
          nameField   = new JTextField(divName, 10);
          // Add the Constraints for the Panel
          GridBagConstraints c = new GridBagConstraints();
          c.insets = new Insets(15,10,0,0);
          c.gridx   =  0;
          c.gridy   =  0;
          add(letterLabel, c);
          c.insets = new Insets(15,10,0,0);
          c.gridx   =  1;
          c.gridy   =  0;
          add(letterField, c);
          c.insets = new Insets(15,10,0,0);
          c.gridx   =  0;
          c.gridy   =  1;
          add(nameLabel, c);
          c.insets = new Insets(15,10,0,0);
          c.gridx   =  1;
          c.gridy   =  1;
          add(nameField, c);
     }// End Main Constructor          
     public String updateVar(int index) {
       if(index == 0)
         return (String)letterField.getText();
       else if(index == 1)
         return (String)nameField.getText();
       else
          System.out.println("Error!");
         return "Error!";
     }// End updateVar
}Here is the snippet of code that calls updateVar
public void doSave()
      JFrame nullframe = new JFrame();
         divLetter = divPane.updateVar(0);
         divName   = divPane.updateVar(1);
         System.out.println(divName);
         System.out.println(divLetter);
}Note: This is a problem from one of my previous posts. (http://forum.java.sun.com/thread.jsp?forum=31&thread=551160&start=15&range=15&hilite=false&q=)

Thank you, how might I reference that function without
making it static.You haven't said if doSave is in the same class or not. If it's in the same class then you are able to call it without another object.
divLetter = updateVar(0);Look at the other posts if you want to know to to access it from another object.
/Kaj

Similar Messages

  • Problem with instantiation in static function

    I have a problem with instatiation of objects in a static function. When I do something like this,
    public static void test1() {
    String s = new String();
    everything works fine, but when I try to do the same with a internally defined class, I get the error "non-static variable this cannot be referenced from a static context".
    My code looks roughly like this:
    public static void test2() {
    Edge e = new Edge();
    class Edge {
    public int y_top;
    public double x_int;
    public int delta_y;
    public double delta_x;
    The compiler complains with the mentioned error message over the creation of a new Edge object and I don't have the slightest clue why... :| When I put the class Edge into an external file, it works.
    Can anyone help me out there?

    Your class Edge is a member of the instance of the current class. You don't have an implicit instance of the current class (the "this" reference) in a static context, therefore you get the error.
    You need to either declare Edge as static, move it outside your class, or create an explicit instance of the outer class which you use to create instances of Edge ("Edge e = new YourMainClass().new Edge()")

  • Static functions

    Hi
    I was wondering ,If I have multiple threads accessing a certain stateless static function,
    do I have to worry about synchronization?
    eg lets say my function is:
    public static int addup(int a,int b,int c)
            ans = a + b + c;
            return ans;
    }Will each thread create its own instance of this function on the stack or will they all use the same one
    possibly causing synchronization problems?
    If indeed there is no synch problem here then shouldn't any stateless function be declared as static?

    Aharon wrote:
    public static int addup(int a,int b,int c)
    ans = a + b + c;
    return ans;
    If this does compile, it's not stateless. ;-)
    To answer the question: Yes, stateless static methods are thread safe. And no, not every stateless method should be static as this prevents the method from being overwritten in subclasses. (On the other hand, this does mean that every private, stateless method may be - and IMHO should be - static.)

  • Does labview support dll which has sub functions that are static functions?

    Dear all,
    I wrote and compiled a C function into dll to be called by labview. The function calls a sub function. It works fine if it is a normal sub function. However I see that if I declare the sub function to be static, labview will crash. So is it that labview does not support static function in dll?
    Best,
    Miao

    A static function simply means that it is local to the C module that defines it and can't be seen from other C modules in a library. It should not change anything else about how it works.
    So in conclusion it should not make a difference in if it crashes or not but only create possible problems in linking the library. It seems extremely likely that you have another problem in your library that gets somehow triggered more easily when you compile your code with the static functions, but it should not have to do anything directly with the fact that you have static functions in itself.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Can not call a static function with-in a instance of the object.

    Another FYI.
    I wanted to keep all of the "option" input parameters values for a new object that
    i am creating in one place. I thought that the easiest way would be to use a
    static function that returns a value; one function for each option value.
    I was looking for a way to define "constants" that are not stored in
    the persistent data of the object, but could be reference each time
    the object is used.
    After creating the static functions in both the "type" and "body" components,
    I created the method that acutally receives the option input values.
    In this method I used a "case" statement. I tested the input parameter
    value, which should be one of the option values.
    I used a set of "WHEN conditions" that called the same
    static functions to get the exact same values that the user should
    pass in.
    When I try to store this new version, I get the error:
    "PLS-00587: a static method cannot be invoked on an instance value"
    It points to the first "when statifc_function()" of the case function.
    This seems weird!
    If I can call the static method from the "type object" without creating
    and instance of an object, then why can't I call it within the body
    of a method of an instance of the object type?
    This doesn't seem appropriate,
    unless this implementation of objects is trying to avoid some type
    of "recursion"?
    If there is some other reason, I can not think of it.
    Any ideas?

    Sorry for the confusion. Here is the simplest example of what
    I want to accomplish.
    The anonymous block is a testing of the object type, which definition follows.
    declare
    test audit_info;
    begin
    test := audit_info(...);
    test.testcall( audit_info.t_EMPLOYER() );
    end;
    -- * ========================================== * --
    create or replace type audit_info as object
    ( seq_key integer
    , static function t_EMPLOYER return varchar2
    , member procedure test_call(input_type varchar2)
    instantiable
    final;
    create or replace type body audit_info
    as
    ( id audit_info
    static function t_EMPLOYER return varchar2
    as
    begin
    return 'EMPLOYER';
    end;
    member procedure test_call(input_type varchar2)
    as
    begin
    CASE input_type
    WHEN t_EMPLOYER()
    select * from dual;
    WHEN ...
    end case;
    end;
    end;
    The error occurs on the "WHEN t_EMPLOYER()" line. This code is only
    an example.
    Thanks.

  • A solution for Secure Static Versioning problem in 1.5.0_10

    Hi,
    I have JRE 1.3.1_09 and 1.5.0_10 on my computer and I think I have solved static versioning problem.
    My test computer:
    - Windows XP sp2
    - Internet Explorer 7 (on another computer also IE 6)
    - Firefox 2.0.0.1
    - JRE 1.3.1_09
    - JRE 1.5.0_10
    I. Solution for Internet Explorer 6 and Internet Explorer 7
    1. Edit registry and add:
    HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Deployment\Policy
    DWORD: EnableSecureStaticVersioning = 0 (Hex)
    2. Restart browser if started.
    3. Start web page with java applet.
    II. Solution for Firefox 2.0.0.1:
    1. Install 1.3 JRE in the same parent directory as 1.5 JRE.
    Because default default installation path for 1.5 JRE is C:\Program Files\Java\jre1.5.0_10 you need to modify
    1.3 installation path from default C:\Program Files\JavaSoft\JRE\1.3.1_09 to C:\Program Files\Java\jre1.3.1_09
    After installation check out that "bin" directory is in the following path:
    C:\Program Files\Java\jre1.3.1_09\bin
    2. Install 1.5 JRE in default installation directory: C:\Program Files\Java\jre1.5.0_10.
    After installation check out that "bin" directory is in the following path:
    C:\Program Files\Java\jre1.3.1_09\bin
    3. Restart browser if started.
    4. Start web page with java applet.
    Note: HTML page must use <object> tabs for Internet Explorer or <embed> tabs for any other browser (e.g. Firefox). You need to specify correct classid in object and/or embed tag.
    P.S. If anyone would like to discuss with me send me an e-mail to [email protected], but please post question to forum and just mail me a link to forum. I will write my answer to forum.
    Hope this helps,
    Grofaty

    I have been trying to find a solution for this issue at our organization for over 6 months. Finally, we have a work around to run multiple java versions for newer and aging java apps.
    Thanks,
    Adunlow

  • Has anyone had a problem with TapMedia File Manage on iPhone 5. I reported a WIFI functionality problem to the developer and asked for support. Instead they have been very unprofessional by name calling me instead of logically evaluate and troubleshoot th

    Has anyone had a problem with TapMedia File Manage installed on iPhone 5? I reported a WIFI functionality problem to the developer and asked for support. Instead the company has been very unprofessional by name calling me instead of logically evaluate and troubleshoot the problem

    Hi AKE1919,
    Welcome to the Support Communities!
    The following information should help you with this:
    How to report an issue with your iTunes Store, App Store, Mac App Store, or iBookstore purchase
    http://support.apple.com/kb/HT1933?viewlocale=en_US
    Cheers,
    Judy

  • Mvc cant access repository classes from static functions in controller(mvc net c# Entity Frame work)

    I working on .net MVC Entity Framework (Code First).
    I am not able to get Datacontext in repository classes functions when i call these functions from a static function in controller . I am getting the Exception
    "An exception of type 'System.NullReferenceException'
    occurred in YYYYYY.Web.dll(Default
    project dll) but was not handled in user code
    Additional information: Object reference not set to an instance of an object."
    i need to call static functions since i had to call some functions asynchronously.Like Report generation
    This works perfectly fine when called from a non static function in controller.
    Thanks in advance
    Punnoose

    But when i call a function in repository class, With dependency Injection(NInject). 
    eg:-
     public Batch GetBatchDetail(string batchID)
                return this.db.Batches.Where(x => x.ID=batchID).FirstOrDefault();
    Db is Datacontext
    I am getting the Exception  "An exception of type 'System.NullReferenceException'
    occurred in YYYYYY.Web.dll(Default
    project dll) but was not handled in user code
    Please do help me
    regards
    punnoose

  • Static function in XSLT

    Hi,
    Could somebody tell me if i can embed a static function (ABAP) in an XSLT.
    Thanks in advance
    Rachana

    Hi,
    Thanks a lot and this should help me. But I'm not that well-versed in XSLT.
    Hence,
    I'm getting an xml namespace not defined error now.
    my XSLT looks like this
    <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:strip-space elements="*"/>
      <xsl:output indent="no"/>
      <xsl:template match="TaskType">
        <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
          <asx:values>
            <TASKTYPEDESIGN>
              <SBTM_CR_TT_DESIGN>
                <ORIGINAL_LANG>
                                 <xsl:value-of select="../@origLang"/>
                </ORIGINAL_LANG>
                <sap:call-external class="CL_SBTM_XML_CONVERSION"              method="GET_SYLANGU">
              <sap:callvalue     param="EXTERNAL"   select="../@language"/>
              <sap:callvariable  param="INTERNAL"   name="SY_LANG"/>
              </sap:call-external>
              </SBTM_CR_TT_DESIGN>
             </TASKTYPEDESIGN>
           </asx:values>
        </asx:abap>
      </xsl:template>
    I tried to fit in that code there...but i guess this is not the way.
    please help

  • Abstract class and static function

    Please tell me that why a static function can't be made abstract?
    Thanks.
    Edited by: RohitRawat on Sep 9, 2009 7:45 AM

    RohitRawat wrote:
    Please tell me that why a static function can't be made abstract?
    Thanks.Because the method belongs to the class.

  • Static function issue?

    hi,
    i am having a static function which fetch some values from data base and put it to an arraylist and return this array list.
    some times the returned array list empty even though values are exists in db,all the varibles used in this static functions are local and
    this function is very frequently acceessing from diffrent threads
    when a static function calls then all the variables in the fuction will have diffrent copies right?
    in my example i wondered like one thread is executing this function then in beetween another thread comes and re initilise the variables so i am getting the abive specified error...
    please any one help ...

    My J2SE version (no EJB's, direct JDBC, no ConnectionPooling) might look something like this, except the connect and close methods are allready in my krc.utilz.jdbc.JDBC class.
    package david;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    import java.util.logging.Logger;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    class Sql
      private final String className;
      private final Logger log;
      private final Connection conn;
      public Sql() throws ClassNotFoundException, SQLException, IOException  {
        className = this.getClass().getName();
        log = Logger.getLogger(className);
        try {
          conn = connect(this.getClass().getResourceAsStream("database.properties"));
        } catch (SQLException e) {
          log.throwing(className, "noargs constructor", e);
          throw e;
       * Executes the given query and returns the resulting rows as a List(rows)
       * of Maps(Column name to value).
       * @param String sql - the sql-select-query to execute
       * @param String[] args - the query paramaters (if
       * @return List<Map<String,String>> rows
       * @throws java.sql.SQLException
      public List<Map<String,String>> select(String sql, String[] args) throws SQLException {
        final String methodName = "select";
        log.entering(className, methodName, new String[] {"sql="+sql, "args="+args});
        List<Map<String,String>> rows = new ArrayList<Map<String,String>>();
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
          stmt = conn.prepareStatement(sql);
          for (int i=0; i<args.length; i++) {
            stmt.setString(i+1, args);
    rs = stmt.executeQuery();
    ResultSetMetaData md = rs.getMetaData();
    int numCols = md.getColumnCount();
    while (rs.next()) {
    Map<String,String> cols = new HashMap<String,String>(numCols);
    for (int c=1; c<=numCols; c++) {
    cols.put(md.getColumnName(c).toUpperCase(), rs.getString(c));
    rows.add(cols);
    } finally {
    close(rs, stmt, null);
    log.exiting(className, methodName, "rows="+rows.size());
    return rows;
    public void close(ResultSet rs, PreparedStatement st, Connection cn) {
    if(rs!=null)try{rs.close();}catch(SQLException e){log.severe(e.toString());}
    if(st!=null)try{st.close();}catch(SQLException e){log.severe(e.toString());}
    if(cn!=null)try{cn.close();}catch(SQLException e){log.severe(e.toString());}
    * Connects to the database specified in the given connectionProperties.
    * @param propertiesStream a java.io.InputStream from which to read
    * java.util.Properties - Example contents:
    * jdbc.driver=com.mysql.jdbc.Driver
    * jdbc.url=jdbc:mysql://localhost/test
    * jdbc.username=user
    * jdbc.password=pass
    * @return Connection - an open connection to the given database.
    * @throws ClassNotFoundException if the class named in the
    * jdbc.driver property can't be initialized.
    * The root cause exception is enclosed.
    * Double check the name of the driver class in the properties file.
    * Ensure that the named driver class exists is in the classpath.
    * @throws SQLException if a database access error occurs.
    * The root cause exception is enclosed.
    * Check the jdbc.url, jdbc.username, and jdbc.password properties.
    private Connection connect(InputStream propertiesStream)
    throws IOException, ClassNotFoundException, SQLException
    Properties props = new Properties();
    props.load(propertiesStream);
    String driver = props.getProperty("jdbc.driver");
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");
    try {
    Class.forName(driver).newInstance();
    } catch (ClassNotFoundException e) {
    throw e;
    } catch (Exception e) {
    String msg = "Failed to connect to url: "+url+" as "+username+" via driver "+driver;
    throw new ClassNotFoundException(msg, e);
    try {
    return DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
    String msg = "Failed to connect to url: "+url+" as "+username+" via driver "+driver;
    throw new SQLException(msg, e);
    BTW... search the forums and you'll find something similar to (but a tad more flexible than) this... I wrote a simple "squirrel" in swing about a year or so ago... execute the query, populate a table with the results.
    Another trick is the close the database connection on ANY SQLException (to keep it clean)... easy when you use a connection pool.
    Cheers. Keith.
    Edited by: corlettk on 7/11/2008 00:47 ~~ Wrong file. Doh!

  • Member /static function and procedure

    hi guys,
    i'm trying to figure out diffrerences between the following;
    1. member function and static function
    2.*member* procdure and static procedure.
    i wanna know when to use them when creating an object type.thanks.

    hope this enlighten you
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/objects.htm#CHDEFBEA

  • Using static function in c++

    Hi,
    I'm using an static function on C++ program, as :
    static int lRead(char ptr, Socket pSock);
    but when I compiled recived the following error:
    Error: "static" is not allowed here.
    any idea about how do i need to set static functions and variables?
    regards,

    You really should provide more information, but the statement looks fine. Probably, you've got a syntax error earlier in the translation unit, possibly in an include file.
    ... Dave

  • How do i create a static function in a class and implement ActionListener?

    i am trying to create a pop up dialog box in a seperate class.
    and i want to make the Function static, so that i only need to access it with the class name.
    But how do i have a ActionListener ?
    everything in a static function is static rite?

    import java.awt.*;
    import java.awt.event.*;
    public class StaticFunction
        Dialog dialog;
        private Panel getUIPanel()
            Button button = new Button("show dialog");
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    if(dialog == null)
                        dialog = OutsideUtility.showDialog("hello world");
                    else if(!dialog.isVisible())
                        dialog.setVisible(true);
                    else if(dialog.isVisible())
                        dialog.dispose();
                        dialog = null;
            Panel panel = new Panel();
            panel.add(button);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        public static void main(String[] args)
            StaticFunction sf = new StaticFunction();
            Frame f = new Frame();
            f.addWindowListener(sf.closer);
            f.add(sf.getUIPanel());
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    class OutsideUtility
        public static Dialog showDialog(String msg)
            Button button = new Button("top button");
            button.setActionCommand(msg);
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    System.out.println(button.getActionCommand() +
                                       " from anonymous inner listener");
            button.addActionListener(new ButtonListener());
            Button anotherButton = new Button("bottom button");
            anotherButton.setActionCommand("another button");
            anotherButton.addActionListener(localListener);
            Panel north = new Panel();
            north.add(button);
            Panel south = new Panel();
            south.add(anotherButton);
            Dialog dialog = new Dialog(new Frame());
            dialog.addWindowListener(closer);
            dialog.add(north, "North");
            dialog.add(new Label(msg, Label.CENTER));
            dialog.add(south, "South");
            dialog.setSize(200,200);
            dialog.setLocation(425,200);
            dialog.setVisible(true);
            return dialog;
        private static WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                Dialog dialog = (Dialog)e.getSource();
                dialog.dispose();
        private static ActionListener localListener = new ActionListener()
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                System.out.println(button.getActionCommand() +
                                   " from localListener");
        private static class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                String ac = button.getActionCommand();
                System.out.println(ac + " from ButtonListener");
    }

  • Is Using Static functions advisable from performance(speed) point of view

    I was wondering if using a static function would be slower than using a normal function, especially when the function is to be accessed by multiple threads since the same memory area is used each time the static function is accessed from any of the threads. Thus is it right if I say that static functions are not suitable for multiThreaded access ?

    I was wondering if using a static function would be
    slower than using a normal function,Static functions are linked at compile time, while normal functions have to be linked based on the runtime type of the object they are called on. This lookup means that static function invocations are likely to be faster.
    especially when
    the function is to be accessed by multiple threads
    since the same memory area is used each time the
    static function is accessed from any of the threads.If you are talking about the code segment, where the function definition is held, there is only a single copy of each "normal" function as well. The code segment is also read-only, so there are no issues with multiple threads reading and executing the same code at the same time.
    There are the normal issues with multi-threaded access to variables in static functions that exist with normal functions.
    Thus is it right if I say that static functions are
    not suitable for multiThreaded access ?Static functions are no safer than non-static functions in terms of thread safety. On the other hand, it is no more dangerous having multiple threads calling a static function than having multiple threads calling a non-static function on the same object. Exactly the same thread safety techniques apply whether you are working in a static or a non-static context.
    With the above in mind, there is a great deal of design difference between static functions and non-static functions. They mean very different things when creating a system, and an operation that is suited for a static function is very likely not appropriate in a non-static context, and vice versa. The important thing is to make sure the design is appropriate for what the system is trying to do.
    The most common use of static functions is for object creation... The Factory design pattern uses static methods to create objects of a given type, the Singleton design pattern uses static methods to allow access to itself.

Maybe you are looking for