Calling a method in a class extended from thread

I'm trying to use two threads of type ThreadTest to call the addNum method in the class below. I found that i couldnt call the addnum method with the instances I created but had to make the addnum method static and then call it with the class name ThreadTest.Is there anyway to get round this? i'm doing this exercise to try and understand synchronisation. Thanks
import java.lang.Thread;
import java.util.*;
class ThreadTest extends Thread implements Runnable{
     private int x;
     private static ArrayList intnumbers = new ArrayList();
     public ThreadTest(int no)
          x=no;
     public void run()
          for (int i=0; i<x; i++)
               try
               System.out.println(i);
               Thread.currentThread().sleep((long)(Math.random() * 1000));
          }catch(InterruptedException e ){e.getMessage();}
     public static void addNum(int n)
          synchronized(intnumbers){
                    intnumbers.add(new Integer(n));
public static void main(String[] args)
     Thread  testThread = new Thread(new ThreadTest(50));
     Thread  testThreadb = new Thread(new ThreadTest(50));
     testThread.start();
     testThreadb.start();
          ThreadTest.addNum(10);
    //*** this gives an error
    //testThread.addNumber(10);
    //testThreadb.addNumber(10);
}

ok here goes again. ;).
import java.lang.Thread;
import java.util.*;
class ThreadTest extends Thread implements Runnable{
     private int x;
     private static ArrayList intnumbers = new ArrayList();
     public ThreadTest(int no)
          x=no;
     public void run()
          for (int i=0; i<x; i++)
               try
               System.out.println(i);
               Thread.currentThread().sleep((long)(Math.random() * 1000));
          }catch(InterruptedException e ){e.getMessage();}
     public static void addNum(int n)
          synchronized(intnumbers){
                    intnumbers.add(new Integer(n));
public static void main(String[] args)
     Thread  testThread = new ThreadTest(50);
     testThread.start();
     //gives error so how can i create 2 instances of testThread and call addNum with them?
     //testThread.addNum(10);
//works ok but I want to call addNum with 2 different threads
     ThreadTest.addNum(10);
}

Similar Messages

  • Call a method of a class file from an Applet

    I have an Applet nmaed CountDown.java in which I have to call a method "doSelect" of a class file named DBConnection.java. How do I do this? Both the Applet and the class file are in the same directory.

    You should put both classes in the same package and create a jar file containing the whole package.
    Make sure the DBConnection class is public or protected and that the method you're trying to call is public or protected.

  • Calling a method of one class from another withing the same package

    hi,
    i've some problem in calling a method of one class from another class within the same package.
    for eg. if in Package mypack. i'm having 2 files, f1 and f2. i would like to call a method of f2 from f1(f1 is a servlet) . i donno exactly how to instantiate the object for f2. can anybody please help me in this regard.
    Thank u in advance.
    Regards,
    Fazli

    This is what my exact problem.
    i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
    both ShopBook.java and DataBean.java lies in the package shoppack.
    in ShopBook i tried to instantiate the object to DataBean as
    DataBean db = new DataBean();
    it shows the compiler error, unable to resolve symbol DataBean.
    note:
    first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
    when i'm trying to compile the ShopBook its telling this error.
    hope i'm clear in explaining my problem. can u please help me?
    thank u in advance.
    regards,
    Fazli

  • How to call a method of another class ?

    Hello,
    I�d like to know how to call a method of another class. I have to classes (class 1 and class 2), class 1 instantiates an object of class 2 and executes the rest of the method. Later, class 1 has to call a method of class 2, sending a message to do something in the object... Does anybody know how to do that ? Do I have to use interface ? Could you please help me ?
    Thanks.
    Bruno.

    Hi Schiller,
    The codes are the following:
    COMECO
    import javax.swing.UIManager;
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    //Main method
    class comeco {
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception e) {
    AGORA testeagora=new AGORA();
    // Code for socket
    int port;
         ServerSocket server_socket;
         BufferedReader input;
         try {
         port = Integer.parseInt(args[0]);
         catch (Exception e) {
         System.out.println("comeco ---> port = 1500 (default)");
         port = 1500;
         try {
         server_socket = new ServerSocket(port);
         System.out.println("comeco ---> Server waiting for client on port " +
                   server_socket.getLocalPort());
         // server infinite loop
         while(true) {
              Socket socket = server_socket.accept();
              System.out.println("comeco ---> New connection accepted " +
                        socket.getInetAddress() +
                        ":" + socket.getPort());
              input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              // print received data
              try {
              while(true) {
                   String message = input.readLine();
                   if (message==null) break;
                   System.out.println("comeco ---> " + message);
    testeagora.teste(message);
              catch (IOException e) {
              System.out.println(e);
              // connection closed by client
              try {
              socket.close();
              System.out.println("Connection closed by client");
              catch (IOException e) {
              System.out.println(e);
         catch (IOException e) {
         System.out.println(e);
    AGORA
    import javax.swing.UIManager;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.net.*;
    //public class AGORA {
    public class AGORA {
    boolean packFrame = false;
    //Construct the application
    public AGORA() {
    try {
    Main frame = new Main();
    System.out.println("agora ---> Criou o frame");
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame)
    frame.pack();
    else
    frame.validate();
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    if (frameSize.height > screenSize.height)
    frameSize.height = screenSize.height;
    if (frameSize.width > screenSize.width)
    frameSize.width = screenSize.width;
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
    catch(Exception e)
    { System.out.println("agora ---> " +e);
    // Tem que criar a THREAD e ver se funciona
    public void remontar (final String msg) {
    try {
                   System.out.println("agora ---> Passou pelo Runnable");
    System.out.println("agora --> Mensagem que veio do comeco para agora: "+ msg);
    Main.acao(msg);
    catch(Exception x) {
    x.printStackTrace();
    MAIN
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.border.*;
    import java.net.*;
    import java.io.*;
    public class Main extends JFrame {
    // ALL THE CODE OF THE INTERFACE
    //Construct the frame
    public Main() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public void acao() {
    // C�digo para mudar a interface
    Runnable setTextRun=new Runnable() {
    public void run() {
    try {
                   System.out.println("main ---> Passou pelo Runnable");
    TStatus.setText("main ---> Funcionou");
    catch(Exception x) {
    x.printStackTrace();
    System.out.println("main ---> About to invokelater");
    SwingUtilities.invokeLater(setTextRun);
    System.out.println("main ---> Back from invokelater");
    // Aqui vai entrar o m�todo para ouvir as portas sockets.
    // Ele deve ouvir e caso haja alguma nova mensagem, trat�-la para
    // alterar as vari�veis e redesenhar os pain�is
    // Al�m disso, o bot�o de refresh deve aparecer ativo em vermelho
    //Component initialization
    private void jbInit() throws Exception {
    // Initialize the interface
    //Setting | Host action performed
    public void SetHost_actionPerformed(ActionEvent e) {
         int port;
         ServerSocket server_socket;
         BufferedReader input;
    System.out.println("main ---> port = 1500 (default)");
         port = 1500;
         try {
         server_socket = new ServerSocket(port);
         System.out.println("main ---> Server waiting for client on port " +
                   server_socket.getLocalPort());
         // server infinite loop
    while(true) {
              Socket socket = server_socket.accept();
              System.out.println("main ---> New connection accepted " +
                        socket.getInetAddress() +
                        ":" + socket.getPort());
              input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String espaco=new String(": ");
         JLabel teste2=new JLabel(new ImageIcon("host.gif"));
              PHost.add(teste2);
    System.out.println("main ---> Adicionou host na interface");
              repaint();
    System.out.println("main ---> Redesenhou a interface");
              setVisible(true);
              // print received data
              try {
              while(true) {
                   String message = input.readLine();
                   if (message==null) break;
                   System.out.println("main ---> " + message);
              catch (IOException e2) {
              System.out.println(e2);
              // connection closed by client
              try {
              socket.close();
              System.out.println("main ---> Connection closed by client");
              catch (IOException e3) {
              System.out.println(e3);
         catch (IOException e1) {
         System.out.println(e1);
    public void OutHost_actionPerformed(ActionEvent e) {
              repaint();
              setVisible(true);
    //Help | About action performed
    public void helpAbout_actionPerformed(ActionEvent e) {
    Main_AboutBox dlg = new Main_AboutBox(this);
    Dimension dlgSize = dlg.getPreferredSize();
    Dimension frmSize = getSize();
    Point loc = getLocation();
    dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
    dlg.setModal(true);
    dlg.show();
    //Overridden so we can exit on System Close
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if(e.getID() == WindowEvent.WINDOW_CLOSING) {
    fileExit_actionPerformed(null);
    public void result(final String msg) {
    // C�digo para mudar a interface
    Runnable setTextRun=new Runnable() {
    public void run() {
    try {
                   System.out.println("main ---> Chamou o m�todo result para mudar a interface");
    System.out.println("main --> Mensagem que veio do agora para main: "+ msg);
    TStatus.setText(msg);
    catch(Exception x) {
    x.printStackTrace();
    System.out.println("main --> About to invokelater");
    SwingUtilities.invokeLater(setTextRun);
    System.out.println("main --> Back from invokelater");
    []�s.

  • How to call java method having array as argument from c++ ?

    Hello sir,
    how to call java method having array as arguments from c++;
    here is java code which is called from c++
    class PQR {
         public void xyz(int[] ia) {
         System.out.println("hi");
              for (int i = 0; i < ia.length; i++)
                   System.out.println(ia);
    suppose all jvm invocation is done...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    For someone well versed in java, C++ and JNI although tedious that should be obvious.
    For someone not well versed in all three it is going to be very difficult.
    Even for someone that does have knowledge in all of those areas coming up with a C++ interface that reflects that functionality in a dynamic way such that anyone is will to use it is going to be quite an adventure.
    At any rate to start building it you do exactly the same thing that you would in java.
    1. Extract everything in the jar via the zip package
    2. For each found instance extract all of the methods, return types, parameters, etc and build a description tree for each class.
    Doing all of that in C++ is going to take a LOT of code. If someone wanted an estimate from me it would take me 6 months to do it. And before I would even attempt it I would get them to explain to me in detail exactly how they thought they were going to use it when I was done because I can't see any reasonable way to do that.
    I left out the description tree itself. I suppose you could duplicate the entire reflection api in C++.
    Now perhaps if it was much, much more constrained, like to only those classes that implement a single interface then that would be more reasonable.

  • Calling a method in the view controller from the component controller

    Hi
    Is there anyway to call a method in the view implementation from the component controller??
    Thanks
    jack

    Thanks for all your replies. I want this kind of a functionality because Im trying to invove a DC (Child DC) from a Parent DC such that the Child DC's view is displayed onto the view container of the Parent DC. I have embedded using 'interface view of a component instance' in the Parent Window and am able to create the component and set usage though the onPlugDefault of the Child View.
    But I observe that when i make a call from the parent, the flow is like this:
    1. The wdDoInit of the Child Component Controller gets triggered first.
    2. Then the wdDoInit of the Child's <b>VIEW</b> gets triggered
    3. and <b>THEN</b> the onPlugDefault of the Child Component Interface View
    What I had actually wanted was to Fire onPlugDefault where Im calling a method LoadData(), after which the Child DC's view must be triggered so it can display the fetched data.
    What is actually happening is the view gets displayed, but no data is displayed in the view.
    Right now I have just given a work around where Im triggering <b>LoadData()</b> of the <b>COmponent COntroller</b> from the <b>wdDoInit</b> of the <b>VIEW</b>.
    Is there a better way to do this? I find it strange that I have to load the Data from the view.
    Thanks
    Jack

  • Calling a Method in other Class

    I want to call a method in another class when an action is preformed can anyone suggest how I might do this??
         addSquare.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
         

    I want to call a method in another class when an
    action is preformed can anyone suggest how I might do
    this??
            addSquare.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent e)
                 {               OtherClass oc = //getrefererncetootherclass
                   oc.methodtocall(params, to, pass);

  • Calling a method in Runnable Class

    Hello I am trying to water this down but how can I call a method in my class
    If I am passed only thread t.
    MyClass mc = new MyClass();
    Thread t = new Thread(mc);
    t.start(); //works because it is a method of Thread
    t.myMethodInMyClass (); // wont work because it cant find it
    I have attempted casting to MyClass but I get CCException.
    Any help would be wonderful..
    cheers and thanks in advance.
    Scott

    Well, you could potentially have too many things in one class. You may want to try and modularize your classes more. But 'if in several situations [you] need different things to run'... well, the logic is just going to have to be there for that in some form.
    Now, if you've already performed the logic to determine what to run and you are going to have to perform the logic again (in your run() method), then there is a flaw in your design.

  • Can we call main method in another class?

    Hi...
    can we call main method in another class?
    If no, please tell me the exact reason why can't we call that....

    ok
    can u give that code for me?
    class A {
    public static void main(String [] args){
    System.out.println("In A");
    class B {
    public static void main(String [] args){
    A.main(null);
    }

  • Calls to methods in a class that extends Thread

    Hello,
    I have some code that I am initiating from within an ActionListener that is part of my programs GUI. The code is quite long winded, at least in terms of how long it takes to perform. The code runs nicely, however once it is running the GUI freezes completely until operations have completed. This is unacceptable as the code can take up to hours to complete. After posting a message on this forum in regard to the freezing of the GUI it was kindly suggested that I use multi-threading to avoid the unwelcome program behaviour.
    The code to my class is as follows:
    public class FullURLAddress
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    I have changed the above code to make use of multithreading by making this class extend Thread and implementing the run() method as follows:
    public class FullURLAddress extends Thread
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
      public void run()
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    /* What happens with these methods, will they need to have their
    own treads also? */
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    Are there any special things that I need to do in regard to the variables returned by the getCount() and xurlAddressDetails() methods. These methods are called by the code that started the run method from within my GUI. I don't understand which thread these methods are running in, obviously there is an AWT thread for my GUI and then a seperate thread for my FullURLAddress objects, but does this new thread also encompass the getCount() and xurlAddressDetails() methods?
    Please explain.
    This probably sounds a little wack, but I don't understand what thread is responisble for the methods in my FullURLAddress class aside of course from the run() method which is obvious. Any help will be awesome.
    Thanks
    Davo

    Threads are part of code that allows you to run multiple operations "simultaneously". "Simultaneously", because threads are not run actually simultaneously in any one-CPU machine. Since you most propably have only one CPU in your system, you can only execute one CPU instruction at time. Basically this means that your CPU can handle only one java-operation at time. It does not matter if you put some code in thread and start it, it will still take up all CPU time as long as the thread runs.
    So you would need a way to let other threads run also, for that purpose thread contains a yield feature that allows you to give time for other threads to run.
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Thread.html#yield()
    You need to use thread's yield() method in your thread code, in a place you want to give other threads time to run. Also bear in mind that if you yield your first thread run to allow second thread to run, you also need to add yield to the second thread also. If you don't, after yielding the first thread, the second thread will eat up all CPU time until it finishes, thus meaning the rest of your first thread will be run after second thread is done.
    One good place to execute yield() is usually at the end of a loop, for example 'for' or 'while' loop. This way you prevent for example while-deadlocks.
    Here is a java thread tutorial, worthy reading:
    http://java.sun.com/docs/books/tutorial/essential/threads/

  • How to call main method in one class from another class

    Suppose i have a code like this
    class Demo
    public static void main(String args[])
    System.out.println("We are in First class");
    class Demo1
    public static void main(String args[])
    System.out.println("We are in second class");
    In the above program how to call main method in demo calss from Demo1 class......???????

    No, i dont know how to call other than main methods from other classes
    And one more doubt i have i.e. Like in C can we see the execution of the program like how the code is being compiled step by step and how the value of the variable changes from step to step like(Add Watch).........

  • How to call a method in IMPL class from one context node

    Hi, I´ve been only study the posibility to access a method in the IMPL class  from one context node class...CN## without using events, is there a way to call it ??? I don´t have it as requierement just learning thanks !.

    Hi,
    Try this by following this you can get the custom controller instacne in the view context nodes, for your requirement you can keep the view implementation class instance instead of cuco..
    To get the custom controller instance in Context node getter/setter method:
    1. Declare Cuco instance reference variable in ctxt class..
    2. Set this cuco ref. in the Create context node method of ctxt class:
    try.
    gr_cucoadminh ?= owner->get_custom_controller( 'ICCMP_BTSHEAD/cucoadminh' ). "#EC NOTEXT
    catch cx_root.
    endtry.
    you can avoid this step as this is not needed in case of view isntance
    3. Assign this instance to the respective context node Create method using:
    BTStatusH->gr_cuco ?= gr_cucoadminh.  " here assign the view implementation ref. " me" instead of gr_cucoadminh
    Here gr_cuco is the ref. variable of custom controller in the respective context node for eg. BtstatusH
    Sample implementation of this can be found in
    ICCMP_BTSHEAD/BTSHeader ->context node BTACTIVITYH-> attr ->GR_CUCO(instance of cuco)
    Cheers,
    Sumit Mittal

  • Calling another method in the class from within the body of a method Im wri

    Hello out there.
    I have a question. I keep getting an error that reads as follows:
    1 error found:
    File: /Users/matthieubell/Academia/University of Waterloo/CS 125/L06/CreditCard.java [line: 80]
    Error: double cannot be dereferenced
    I think it is occuring because I am trying to call a method on an instance variable, which is not an object. But how do call a method I have already written, on another method I am writing in the general sense. I could make a particular object, but Im not shure that would get me the same result. I want to be able to call the method calcMinPayment on the instance variable currentBalance to wirte the method makePayment.
    I have a class CreditCard
    with the instance variables "private double currentBalance = 0; "
    public double calcMinPayment()
    // Add code here
    double minimumPayment;
    if (currentBalance < 50)
    minimumPayment = currentBalance/10;
    else
    minimumPayment = 50;
    return minimumPayment; // Replace this statement
    * This method will decrease the current balance on the credit card if
    * this payment meets or exceeds the minimum payment amount.
    * pre: paymentAmt > 0
    * post: The current balance should be decreased by paymentAmt if
    * paymentAmt >= the minimum payment amount. Otherwise, the payment
    * will not be recorded and an appropriate error message should be
    * displayed.
    public void makePayment(double paymentAmt)
    // Add code here
    double minimumPaymentAmount;
    minimumPaymentAmount = currentBalance.calcMinPayment();
    if (paymentAmt < minimumPaymentAmount)
    System.out.println("Sorry, but your payment must exceed the minimum payment amount.");
    System.out.println("This payment has not been recorded, please try again.");
    else
    this.currentBalance = currentBalance - paymentAmt;
    thanks for youre help
    -Matthieu

    'calcMinPayment' takes no arguments, uses a member variable (currentBalance) to compute a local variable 'minimumPayment' which it returns, ie, sends back to the caller. So you can call 'calcMinPayment' at any time.
    minimumPaymentAmount = calcMinPayment();

  • How do i call the method in a class using servlet

    i am doing a project which need to use servlet to call a few methods in a class and display those method on the broswer. i tried to write the servlet myself but there are still some errors .. can anyone help:
    The servlet i wrote :
    package qm.minipas;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class test extends HttpServlet {
    Database database;
    /** Initializes the servlet.
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    database = FlatfileDatabase.getInstance();
    /** Destroys the servlet.
    public void destroy() {
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("this is my class wossname"+FlatfileDatabase.getInstance()); // this is calling the toString() method in the instance of myJavaClass
    out.println("this is my method"+FlatfileDatabase.getAll());
    out.println("</body>");
    out.println("</html>");
    out.close();
    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    my methods which i need to call are shown below:
    public Collection getAll() {
    return Collections.unmodifiableCollection(patientRecords);
    public Collection getInpatients() {
    Collection selection=new ArrayList();
    synchronized(patientRecords) {
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(next.isInpatient())
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByAdmissionDate(Date dateOfAdmission) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(dateOfAdmission.equals(next.getDateOfAdmission()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByAdmissionDates(Date from,Date to)
    throws IllegalArgumentException {
    if(to.before(from))
    throw new IllegalArgumentException("End date must not be before start date");
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    Date nextAD=next.getDateOfAdmission();
    if((nextAD.after(from)||nextAD.equals(from))
    &&(nextAD.before(to)||nextAD.equals(to)))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByDischargeDates(Date from,Date to)
    throws IllegalArgumentException {
    if(to.before(from))
    throw new IllegalArgumentException("End date must not be before start date");
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    Date nextAD=next.getDateOfDischarge();
    if(nextAD==null)
    continue;
    if((nextAD.after(from)||nextAD.equals(from))
    &&(nextAD.before(to)||nextAD.equals(to)))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByConsultant(String consultant) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(consultant.equalsIgnoreCase(next.getConsultant()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByDischargeDate(Date dateOfDischarge) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(dateOfDischarge.equals(next.getDateOfDischarge()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getBySurname(String surname) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(surname.equalsIgnoreCase(next.getSurname()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByWard(String ward) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(ward.equalsIgnoreCase(next.getWard()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);

    please provide a detail description of your errors.

  • Trying to call a method on an RMI server from a GUI

    Hi all, I'm new to the forums and I desperately need some help!
    My question fits into the RMI category but also the database/GUI side so sorry if this is posted in the wrong place.
    My application is a client/server system (programmed in Netbeans 6.8) that also uses GUIs and JDBC-ODBC. Basically, I am trying to call a method that adds an entry to my database from a GUI button.
    Due to the required RMI, I have the ServerInterface that extends Remote and I have a ServerImpl class that implements the Interface, and the RMI works fine so there is no problem there.
    My code for the button is:
    private void addUserActionPerformed(java.awt.event.ActionEvent evt) {                                       
    try{server.addNewUser("new");}
    catch(Exception e){}
    addUser.setText("buttonhaschanged");
    The server variable is declared above as ServerImpl server;
    The actual addNewUser method works fine when it is called explicitly via RMI in my main "Client" class, but this GUI is going to be like an "administrator GUI" that can manipulate the database, so there is no RMI involved here.
    Anyway, my button doesn't have any effect on the database, but the button changes text as desired so the button itself works, but it doesn't do what I want to the database, so I think my problem is the use of my "server" variable. I've tried making it static and I've tried making it of type ServerInterface, but no luck. Would I have to make the GUI class extend the interface too?
    Sorry for rambling on!
    Many thanks in advance
    David
    Edited by: DHD on Feb 26, 2010 6:15 AM

    Would I have to make the GUI class extend the interface too?Your GUI has nothing to do with the RMI. How did you obtaint the "server" ? have you looked in the RMI registry to get the stub object ?
    The second thing to notice is you are invoking a RMI calls on a EDT which you should not do it. Your RMI method calls should be invoked via SwingWorker-->doInBackground(); please take a look at the Java Doc
    [http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html|java Doc SwingWorker sample usage]
    You mentioned that the RMI method invocation works fine from the main class and not from the GUI so what did you do in the main class to get the stub do it in the doInBackground() method
    Regards,
    Alan
    London

Maybe you are looking for

  • Receive an ORA-01403: no data found error after importing

    After making changes to an application and exporting it and importing it into another applications (copy of the app) on the same server I recieve this error. Error Single Sign-On Procces Failed However if I export and import the application to a diff

  • External hard drive files suddenly not readable

    This keeps happening to my hard drives for no apparent reason.  I use an external drive to backup my macbook pro contents, eventually, I cannot open the files.  I get an error message saying they may be damaged and their preview icon defaults back to

  • How to pass the primary key from a report to multiple forms

    I am trying to build an application that tracks a person's training records. I have a report and 3 forms (all tabbed). From the report I can click the edit link to modify a person. Is there a way I can pass the primary key of the person (from the rep

  • Problem uploading music from iPod to iTunes...please help!!

    Dear All, I originally had all my music on iTunes on a laptop and I quite happily ripped new CDs onto my laptop and updated my iPod from time to time. Then the lap top disappeared and I got a new desk top PC. I thought it would be a simple job to tra

  • Error in OTL Workflow

    Hi, I have defined the time categories.. One project was missed out, so when i submitted a time sheet it errored out. Now i have added it, and tried submitting new sheet with same data which worked but when i tried to rewind the existing one, it rema