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.

Similar Messages

  • How to call a method from another class

    I have a problem were i have to call a method from another class. What is the command line that i have to use. Thanks.

    Here's one I wipped up in 10 minutes... Cool!
    package forums;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import krc.utilz.io.Filez;
    import java.io.FileNotFoundException;
    class FileDisplayer extends JFrame
      private static final long serialVersionUID = 0L;
      FileDisplayer(String filename) {
        super(filename);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(600, 800);
        JTextArea text = new JTextArea();
        try {
          text.setText(Filez.read(filename));
        } catch (FileNotFoundException e) {
          text.setText(e.toString());
        this.add(text);
      public static void main(String args[]) {
        final String filename = (args.length>0 ? args[0] : "C:/Java/home/src/forums/FileDisplayer.java");
        try {
          java.awt.EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                new FileDisplayer(filename).setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
    Filez.read
       * reads the given file into one big string
       * @param String filename - the name of the file to read
       * @return the contents filename
      public static String read(String filename) throws FileNotFoundException {
        return Filez.read(new FileReader(filename));
       * Reads the contents of the given reader into one big string, and closes the reader.
       * @param java.io.Reader reader - a subclass of Reader to read from.
       * @return the whole contents of the given reader.
      public static String read(Reader in) {
        try {
          StringBuffer out = new StringBuffer();
          try {
            char[] bfr = new char[BFRSIZE];
            int n = 0;
            while( (n=in.read(bfr,0,BFRSIZE)) > 0 ) {
              out.append(bfr,0,n);
          } finally {
            if(in!=null)in.close();
          return out.toString();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
      }Edited by: corlettk on Dec 16, 2007 1:01 PM - dang [code [/tags][                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to call a method in another class ?

    how can i use getUserID method in my main.as  ??
    NetConnectionClient.as
    package com {
    import flash.events.EventDispatcher;
    import flash.events.Event;
    public class NetConnectionClient extends EventDispatcher {
         public static const ONUSERID:String = "onUserID";
         private var _uID :Number;
         public function setUserID(uID:Number):void {
             _uID : uID;
            dispatchEvent(new Event(NetConnectionClient.ONUSERID));
         public function getUserID():Number {
            return _uID;
    Thanks!

    package{
    import com.NetConnectionClient;
    import com.NetConnectionClientEvent;
    import com.NetConnectionManager;
    import fl.data.DataProvider;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.NetStatusEvent;
    import flash.events.SecurityErrorEvent;
    import flash.events.SyncEvent;
    import flash.net.SharedObject;
    import fl.data.DataProvider;
    import fl.video.FLVPlayback;
    import flash.display.MovieClip;
    public class MainAdm extends Sprite{
      private var nc:NetConnectionManager;
      private var so:SharedObject;
      private var soEl:SharedObject;
      private var selectedUser:Number = 0;
      private var userID:String;
      public function MainAdm(){
       nc=new NetConnectionManager();
       nc.addEventListener("onConnect",onConnect);
       nc.client = new NetConnectionClient();
       nc.client.addEventListener("onUserID",onUserId);
       nc.client.addEventListener("onReceiveChatMsg",onReceiveChatMsg);
       nc.client.addEventListener("onElKaldirMsg",onElKaldirMsg);
       nc.client.addEventListener("ongetUserID",ongetUserID);
         i want to trace it here   
         trace(?????.getUserID().toString());
       sendButton.label = "Send Message";
       sendButton.addEventListener(MouseEvent.CLICK,onSendButtonClicked);
       deselectButton.label = "clear";
       deselectButton.addEventListener(MouseEvent.CLICK,onDeselectButtonClicked);
       /*chatInputText.addEventListener(Event.CHANGE,onEnterPressed);*/
       usersList.addEventListener(Event.CHANGE,onUserSelected);  
       /*sendButton.enabled =
       chatInputText.enabled = false;*/
       elKaldir.label = "El Kaldir";
       elKaldir.addEventListener(MouseEvent.CLICK,onElKaldir);
       /*usersTList.columnWidth = 100;
       usersTList.rowHeight = 100;
       usersTList.columnCount = 1;
       usersTList.rowCount = 2;
       usersTList.move(30, 250);*/
       nc.createNetConnection("rtmp://localhost/FMSTutorial22");

  • How do you call a method from  another class without extending as a parent?

    How do you call a method from another class without extending it as a parent? Is this possible?

    Why don't you just create an instance of the class?
    Car c = new Car();
    c.drive("fast");The drive method is in the car class, but as long as the method is public, you can use it anywhere.
    Is that what you were asking or am I totally misunderstanding your question?
    Jen

  • Calling a method from another class... that requires variables?

    I'm calling a method from another class to change the date (its a date object) in another class.
    I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
    My code is:
    public int changeDate()
         cycleDate.setDate();
    }I'm guessing I need to pass 3 parameters (day, month, year), but I'm not sure how! I have tried, but then I get errors such as ')' expected?
    Any ideas! :D

    f1d wrote:
    I'm calling a method from another class to change the date (its a date object) in another class.
    I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
    My code is:
    public int changeDate()
    cycleDate.setDate();
    }I'm guessing I need to pass 3 parameters (day, month, year), seems that way from the error you posted
    but I'm not sure how!
    setDate(16, 6, 2008);
    I have tried, but then I get errors such as ')' expected?
    Any ideas! :Dyou need to post your code if you're getting specific errors like that.
    but typically ')' expected means just that, you have too many or not enough parenthesis (or in the wrong place, etc.)
    i.e. syntax error

  • Help on Calling a method from another class

    how can i call a method from another class.
    Class A has 3 methods
    i just want to call only one of these 3 methods into my another class.
    How can I do that.

    When i am trying this
    A a=new A;
    Its calling all the methods from class A. I just want
    to call a specfic method.How can it be done?When i am trying this
    A a=new A();
    Its calling all the methods from class A. I just want to call a specfic method.How can it be done?

  • Can't add list element when calling a method from another class

    I am trying to call a method in another class, which contains code listmodel.addElement("text"); to add an element into a list component made in that class.
    I've put in System.out.println("passed"); in the method just to make sure if the method was being called properly and it displays normally.
    I can change variables in the other class by calling the method with no problem. The only thing I can't do is get listmodel.addElement("text"); to add a new element in the list component by doing it this way.
    I've called that method within it's class and it added the element with no problem. Does Java have limitations about what kind of code it can run from other classes? And if that's the case I'd really like to know just why.

    There were no errors, just the element doesnt get added to the list by doing it this way
    class showpanel extends JPanel implements ActionListener, MouseMotionListener {
           framepanel fp = new framepanel();
           --omitted--
         public void actionPerformed(ActionEvent e){
                  if(e.getSource() == button1){
                       fp.addLayer();
    /*is in a different class file*/
    class framepanel extends JPanel implements ActionListener{
            --omitted--
         public void addLayer(){
              listmodel.addElement("Layer"+numLayer);
              numLayer++;
    }

  • 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);
    }

  • 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).........

  • Calling repaint method from another class

    My question in a very simple form :
    how do I call repaint mathod from another class.
    e.g: Let's say class "A.java" is a JFrame .
    Class "B.java" is a JPanel which is added to the JFrame above.
    Class "C.java" is a JDialog containing some JButtons.
    How do I call the repaint method from the class "C.java".
    Thank you in advance!!

    My question in a very simple form :
    how do I call repaint mathod from another class.
    e.g: Let's say class "A.java" is a JFrame .
    Class "B.java" is a JPanel which is added to the JFrame above.
    Class "C.java" is a JDialog containing some JButtons.
    How do I call the repaint method from the class "C.java".
    Thank you in advance!!

  • How call a method from another class

    i make three class.class A,class B and class C.
    class A have One button.
    Class B have a action listener of that button.
    class c have a metod like
    public void test(){     }
    how can i call a method in class b from class c;
    is it necessary to pass the class a or b through the constructor of class c or another way to call the method.

    public class Foo
        public static void main(String[] args)
            Bar.staticFn();
            Bar b = new Bar();
            b.memberFn();
    class Bar
        public void memberFn()
            System.out.println("memberFn");
        public static void staticFn()
            System.out.println("staticFn");
      }

  • 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.

  • 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

  • Calling main method in another class using command line arguements

    Hi
    My program need to use 4 strings command line arguments
    entered in Project properties/Run/Application Parameters
    java programming for beginners // arguments
    The program needs to call main in the second class 4 times using argument 1 the first call, argument 2 the second call on so on.
    So the output wil be
    java
    programming
    for
    beginners
    import java.lang.*;
    public class First extends Second{
      public static void main(String[] args) {
        for(int i = 0; i < args.length; i++){
           Second.main(args); // Error I think
    import java.lang.*;
    public class Second {
    public static void main(String[] args){
    System.out.println(args[0]);
    "First.java": Error #: 300 : method main(java.lang.String) not found in class Second at line 6, column 15
    I am only a beginner with little knowledge of java so can the code be as basic as possible

    Your style looks quite bad for starters..... Hows
    this://import java.lang.*; /* NOT NEEDED */
    public class First extends Second{
    public First(String s) {
    super(s);
    public static void main(String[] args) {
    for(int i = 0; i < args.length; i++){
    new First(s);
    public class Second {
    public Second(String s)
    System.out.println(s);
    NOT NEEDED:
    public static void main(String[] args){
    System.out.println(args[0]);
    }My question to you: Do you understand why my code
    works? (does it do what you want?)I think since this is some kind of lesson, the OP have to implement some way to use the main method of the Second class as it is, that is, with String[] args. I think this lesson is interesting exactly because of this requirenment. But, anyway, I don�t know, that is just my assumption...

  • Calling a method from another class or accessing a component from another

    Hi all
    im trying to make a find/replace dialog box
    my main application form has a jtextpane and when i open up the find and replace dialog box it has two textboxes (find and replace)
    now i have the code to do the finding on my jtextpane but how do i call that code to do the find method?
    I have tried having the code in my main application class but then how do i call that method from my dialog box class?
    ive also tried having the code in my dialog box class, but then how to i tell it to work on my jtextpane which is in my main ap class?

    well if someone had been nice enough to provide me
    with a tutorial i wouldnt have gotten into this
    muddle, no need to be rude is there!I'm not rude. And you also wouldn't have gotten into the muddle if you searched yourself. This site provides many very good tutorials about all kinds of stuff.
    http://java.sun.com/docs/books/tutorial/java/javaOO/classes.htmlAmong other things, it mentions that "static" defines everything that belongs to a class, as opposed to an object.

Maybe you are looking for

  • On a HP Officejet Pro L7780 All-in-One printer, is there a toner and where is it?

    On a HP Officejet Pro L7780 All-in-One printer, is there a toner and where is it located? I've looked in Products and Supplies and don't see it but my printer is saying that it's low or empty.

  • Since the IOS update on my iPod touch I get no notification sounds

    I have deleted texting app and reinstalled, all notification sounds are on and up. I have my iPod so it never shuts down and still nothing. When I have the app open I have to pull down the page to refresh b4 notification comes through. Please help b4

  • EWM GR not to ERP

    Hi Gurus I finished GR in EWM(7.0)  by inbound dilevery,but not success in ERP (AFS). and I found the error  'internal error SELECT_ASN_DATA AT_TMSTMP' by SMQ2 and I found the total error as fellowing Internal error SELECT_ASN_DATA AT_TMSTMP Internal

  • Anyone have a solution to stop 3b error in vista pointing to ctaud2k.sys

    Currently running Vista ultimate 64 bit with X-Fi Fatality card.Been getting Stop 0x3B error pointing to ctaud2k.sys after system runs for several hours. I've been pretty proacti've in seeking a solution, but haven't been able to find one. I've alrea

  • Syndication Map Change Track

    Hi Experts, Somebody have changed the map in MDM Syndicator and created huge problem in PI. can we track the User Name who last changed the map? Thanks, Sekhar