How to invoke methods from an other class?

Hello,
I've got the following problem I can't solve:
I have a class that extends JApplet (viewtiff) and another that displays the images (DisplayJAI). Now I have implemented the MouseListener in DisplayJAI and on a right-click it should execute a method located in viewtiff.
If viewtiff would be created by myself with the new operator, this wouldn't be a problem. I just had to write instance_name.method() to invoke it, but in this case I don't know the instance name of my viewtiff class because it gets created by the JApplet I think.
Defining viewtiff static would help, but this isn't possible for the 'main' class in an applet. What can I do now?
Many thanks,
Sebastian Tyler

in the constructor// in ViewApplet:
ViewTIFF vt = new ViewTIFF (this);
// in ViewTIFF:
class ViewTIFF {
private ViewApplet va;
public ViewTIFF (ViewApplet va) {
this.va = va;
void someMethod () {
va.someMethod ();
}>> a setter method// in ViewApplet:ViewTIFF vt = new ViewTIFF ();
vt.setViewApplet (this);
// in ViewTIFF:
class ViewTIFF {
private ViewApplet va;
public void setViewApplet (ViewApplet va) {
this.va = va;
void someMethod () {
va.someMethod ();

Similar Messages

  • How to invoke method from swing

    Aloha,
    Thanks in advance for help...
    I have created GUI, and want to use buttons to choose which Physics problem to solve. I have already coded the Physics in .java and have different methods for each one. I would like for the button to create an action that places the different problems on the panel, each with a section for information, given input and outputting the answers to solve for.
    public void actionPerformed(ActionEvent e)
         { // [20]
               String actionCommand = e.getActionCommand();
               if (e.getActionCommand().equals("Quiz 1"))
                 Quiz1();
               }Quiz1 is a private void method that calls on a helper method to perform calculations.
    When I use the above command, it invokes the method, but not on the GUI panel, it comes up on the DOS screen. What command should I use to place the calculations and information for this method on the GUI? I know I need to separate and create areas of the panel for input, etc. But I want the method to take place on the GUI.
    Thank you for your time and energy.

    Hi - I have a question now regarding using a single button, to collect data from multiple fields, make calculations and then return figures to multiple fields.
    I thought I could read them into two different variables (valueIn, valueIn2, etc) and then apply them to the JTextField variables. I was experimenting with just passing the initial figures without making calculations...
    But just trying with two different fields, the compiler gives me an error for an "unreachable statement". How do I collect from multiple sources and return separate answers to different fields?
    I tried to look up definitions for compiler messages, but couldn't find anything regarding "unreachable statements". Therefore, I would also appreciate any suggestions about a dependable source to reference errors.
    Thank you in advance for your assistance, I am attaching copy of code below...
    public class ChoiceFrame extends JFrame implements ActionListener
    { // [1]
         SolveIt converter = new SolveIt();
         public static final int WIDTH = 650;
      public static final int HEIGHT = 500;
      private JTextArea infoText;
      private double valueIn = 0;
      private double valueIn2 = 0; 
      private JTextField cliffHt;
      private JTextField deceleration;
      private JTextField timeFlight;
      private JTextField height;
      public static void main(String[] args)
      { // [2]
              ChoiceFrame myWindow = new ChoiceFrame();
              myWindow.setVisible(true);
         } // [2]
         public ChoiceFrame()
         { // [3]
              super( );
              setSize(WIDTH, HEIGHT);
              setTitle("ChoiceFrame");       
              Container contentPane = getContentPane();
              contentPane.setBackground(Color.BLUE);
              contentPane.setLayout(new BorderLayout());
              addWindowListener(new WindowDestroyer());                     
              JMenu memoMenu = new JMenu("File");
        JMenuItem file;
        file = new JMenuItem("Clear");
        file.addActionListener(this);
        memoMenu.add(file);
        file = new JMenuItem("Exit");
        file.addActionListener(this);
        memoMenu.add(file);
        JMenuBar mBar = new JMenuBar( );
        mBar.add(memoMenu);
        setJMenuBar(mBar);     
              JPanel northPanel = new JPanel();   
              northPanel.setLayout(new BorderLayout());          
              JPanel textPanel = new JPanel();          
        northPanel.add(textPanel, BorderLayout.WEST);       
              infoText = new JTextArea (8, 43);
              infoText.setBackground(Color.WHITE);
              infoText.setLineWrap(true);
              textPanel.add(infoText);
        infoText.setText("The Coyote, in his relentless attempt to catch the elusive Road Runner,\nloses his footing and falls from a sheer cliff ___ meters above the ground.\nAfter falling for __ seconds (without friction), the Coyote remembers that\nhe is wearing his Acme rocket-powered backpack, which he immediately turns on.\nThe Coyote makes a gentle landing (zero velocity) on the ground below,\nbut is unable to turn off the rocket, and is immediately propelled back up into the air.\n___ seconds after leaving the ground, the rocket runs out of fuel.\nAfter continuing upwards for a ways, the poor Coyote plunges back to the ground.");
              JPanel inputPanel = new JPanel();          
        northPanel.add(inputPanel, BorderLayout.EAST);      
              inputPanel.setLayout(new GridLayout(3,2));     
              cliffHt = new JTextField(5);
              inputPanel.add(cliffHt);
              JLabel mtrsLabel = new JLabel("meters");
              inputPanel.add(mtrsLabel);
              JTextField secondsf = new JTextField(5);
              inputPanel.add(secondsf);
              JLabel sfLabel = new JLabel("seconds falling");
              inputPanel.add(sfLabel);
              timeFlight = new JTextField(5);
              inputPanel.add(timeFlight);
              JLabel sFlightLabel = new JLabel("seconds in flight");
              inputPanel.add(sFlightLabel);          
              JPanel southPanel = new JPanel();          
              southPanel.setLayout(new BorderLayout());          
              JPanel buttonPanel = new JPanel();
              buttonPanel.setLayout(new FlowLayout());
              JButton calcButton = new JButton("Calculate");
              calcButton.addActionListener(this);
              buttonPanel.add(calcButton);
              southPanel.add(buttonPanel, BorderLayout.NORTH);
              JPanel outputPanel = new JPanel();
           outputPanel.setLayout(new GridLayout(3,2));          
              JLabel decelLabel = new JLabel("With the rocket backpack turned on, the deceleration is: ");
              outputPanel.add(decelLabel);
              deceleration = new JTextField(10);
              outputPanel.add(deceleration);
              JLabel htLabel = new JLabel("the max height is: ");
              outputPanel.add(htLabel);
              height = new JTextField(10);
              outputPanel.add(height);
              JLabel vLabel = new JLabel("the velocity is: ");
              outputPanel.add(vLabel);
              JTextField velocity = new JTextField(10);
              outputPanel.add(velocity);          
           southPanel.add(outputPanel, BorderLayout.CENTER);
              contentPane.add(northPanel, BorderLayout.NORTH);                         
              contentPane.add(southPanel, BorderLayout.CENTER);     
         } // [3]
         public void actionPerformed(ActionEvent e)
         { // [20]
              String actionCommand = e.getActionCommand();
              if (e.getActionCommand().equals("Calculate"))
                        deceleration.setText(Quiz1());
                        height.setText(Quiz1());
              else if (e.getActionCommand().equals("Close"))
                   System.exit(0);
              else if (actionCommand.equals("Exit"))
          System.exit(0);
         } //[20]
         private String Quiz1()
         { // [40]
              SolveIt calculate = new SolveIt();
              double gravity = 9.81;
              double initialSpeed = 0;
              double freeFall = 5; //this is time for freefall in seconds
              valueIn = stringToDouble(cliffHt.getText());
              return Double.toString(valueIn);     
              valueIn2 = stringToDouble(timeFlight.getText());          
              return Double.toString(valueIn2);
         } // [40]     
         private static double stringToDouble(String stringObject)
         { // [30]
              return Double.parseDouble(stringObject.trim());
         } // [30]

  • How to override methods from dynamic instaniated class to call externally?

    Hi,
    Does anyone knows how to get processWindowEvent() from JFrame to call externally without having to override it in a subclass.
    public class UserFrame extends JFrame {
    public class Application {
    public void main(String[] args) {
    UserFrame frame = (UserFrame ) UserFrame .class.newInstance();
    processWindowEvent(WindowEvent evt) {
    the point is to get the instantiated UserFrame to call Application's processWindowEvent() whenever the window event is generated without having to override it in UserFrame.
    Any expert on this?

    The point is there will be several subclasses of JFrame and I would not want to mannually override each subclasses, but by getting any JFrams's method to be delegated to call another method. VB.net, Delphi and etc. have a feature called class method delegation.
    Java has a feature called method Proxy by using InvocationHandler class but is there any example how it could perform what I require?

  • How do I call an Application Module method from a EntityImpl class?

    Guys and Gals,
    Using Studio Edition Version 11.1.1.3.0.
    I've got a price update form, that when submitted, takes the part numbers and prices in the form and updates the corresponding Parts' price in the Parts table. Anytime this Parts view object's ReplacementPrice attribute is changed, an application module method needs to be called which updates a whole slew of related view objects. I know you can modify view objects via associations (How do I call an Application Module method from a ViewObjectImpl class? but that's not what I'm trying to do. These AppModuleImpl methods are the hub for all price updates, as many different operations may affect related pricing (base price lists, price buckets, etc) and hence, call the updatePartPricing(key) method.
    For some reason, the below code does not call / run / activate the application module's method. The AppModuleDataControl exists and recordPartHistory(key) is registered and public. At runtime, the am.<method> code is simply ignored, and as a weird side-effect, I cannot navigate out of my current page flow.
      public void setReplacementPrice(Number value)
        setAttributeInternal(REPLACEMENTPRICE, value);
        AppModuleImpl am = (AppModuleImpl)this.getDBTransaction().findApplicationModule("AppModuleDataControl");
        Key key = new Key(new Object[]
            { getPartNumber() });
        am.recordPartHistory(key);  // AppModuleImpl method which records pricing history
        am.updatePartPricing(key); // AppModuleImpl method which updates a whole slew of related pricing tables
      }Any ideas?

    Thanks Timo.
    Turns out the code provided was correct, but the AppModuleImpl method being called was not. A dependent ViewObject wasn't returning the row I was expecting. I then tried to perform some operations on that row, which in turn ... just stopped everything, but didn't give me an error.
    It was the lack of the error that threw me off. I had never messed with calling an AppModuleImpl method from the EntityImpl so I assumed that's what was messing up.
    You are correct. It is available from the ViewRow, but I thought it better to put it in the EntityImpl. This method will be called every time the replacement cost is modified. If I didn't put it in the EntityImpl, I'd have to remember to call it every time a replacement cost changed.

  • Is Two Classes that call methods from each other possible?

    I have a class lets call it
    gui and it has a method called addMessage that appends a string onto a text field
    i also have a method called JNIinterface that has a method called
    sendAlong Takes a string and sends it along which does alot of stuff
    K the gui also has a text field and when a button is pushed it needs to call sendAlong
    the JNIinterface randomly recieves messages and when it does it has to call AddMessage so they can be displayed
    any way to do this??

    Is Two Classes that call methods from each other possible?Do you mean like this?
       class A
         static void doB() { B.fromA(); }
         static void fromB() {}
       class B
         static void doA() { A.fromB(); }
         static void fromA() {}
    .I doubt there is anyway to do exactly that. You can use an interface however.
       Interface IB
         void fromA();
       class A
         IB b;
         A(IB instance) {b = instance;}
         void doB() { b.fromA(); }
         void fromB() {}
       class B implements IB
         static void doA() { A.fromB(); }
         void fromA() {}
    .Note that you might want to re-examine your design if you have circular references. There is probably something wrong with it.

  • Calling a method from a super class

    Hello, I'm trying to write a program that will call a method from a super class. This program is the test program, so should i include extends in the class declaration? Also, what code is needed for the call? Just to make things clear the program includes three different types of object classes and one abstract superclass and the test program which is what im having problems with. I try to use the test program to calculate somthing for each of them using the abstract method in the superclass, but its overridden for each of the three object classes. Now to call this function what syntax should I include? the function returns a double. Thanks.

    Well, this sort of depends on how the methods are overridden.
    public class SuperFoo {
      public void foo() {
         //do something;
      public void bar(){
         //do something
    public class SubFoo extends SuperFoo {
       public void foo() {
          //do something different that overrides foo()
       public void baz() {
          bar(); //calls superclass method
          foo(); //calls method in this (sub) class
          super.foo(); //calls method in superclass
    }However, if you have a superclass with an abstract method, then all the subclasses implement that same method with a relevant implementation. Since the parent method is abstract, you can't make a call to it (it contains no implementation, right?).

  • Need help calling a method from an immutable class

    I'm having difficulties in calling a method from my class called Cabin to my main. Here's the code in my main              if(this is where i want my method hasKitchen() from my Cabin class)
                        System.out.println("There is a kitchen.");
                   else
                        System.out.println("There is not a kitchen.");
                   }and here's my method from my Cabin class:public boolean hasKitchen()
         return kitchen;
    }

    You should first have an instance of Cabin created by using
       Cabin c = ....
       if (c.hasKitchen()) {
         System.out.println("There is a kitchen.");
       } else {
            System.out.println("There is not a kitchen.");
       }

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • Invoke methods from remote cache

    Hi, Guys
         I want to invoke methods from remote cache node WITHOUT joining the cluster.
         Do you provide some mechanism to implement this?
         Currently, I set up an empty cache which joined the same cluster to invoke methods.
         Thanks for your support.

    I want to invoke methods from remote cache node     > WITHOUT joining the cluster.
         > Do you provide some mechanism to implement this?
         Absolutely. It is the "client/server" extension to Coherence, which is called Coherence*Extend.
         See:
         http://wiki.tangosol.com/display/COH32UG/Configuring+and+Using+Coherence*Extend
         Peace,
         Cameron Purdy
         Tangosol Coherence: The Java Data Grid

  • How to call a method from a separate class using IBAction

    I can't work out how to call a method form an external class with IBAction.
    //This Works 1
    -(void)addCard:(MyiCards *)card{
    [card insertNewCardIntoDatabase];
    //This works 2
    -(IBAction) addNewCard:(id)sender{
    //stuff -- I want to call [card insertNewCardIntoDatabase];
    I have tried tons of stuff here, but nothing is working. When i build this I get no errors or warnings, but trying to call the method in anyway other that what is there, i get errors.

    Can you explain more about what you are trying to do? IBAction is just a 'hint' to Interface Builder. It's just a void method return. And it's unclear what method is where from your code snippet below. is addNewCard: in another class? And if so, does it have a reference to the 'card' object you are sending the 'insertNewCardIntoDatabase' message? Some more details would help.
    Cheers,
    George

  • How to use methods from a JAR file inside my springcontext (Oracle fusion 12c) class file?

    Dear Friends,
    I have a jar file, which has executed classes and methods in it. I want to make use of these methods inside my springcontext piece of code.
    Can someone please share an example  of how to write spingcontext code which is accessing classes/methods from  JAR files along with the any setup?
    Thanks,

    I have found the answer... as described in:
    http://java.sun.com/javase/6/docs/technotes/guides/lang/resources.html
    the problem was that the properties are loaded with the getResource & getResourceAsStream methods and I didn't know that one. I thought that is was loaded through findClass because I saw the property files trying to be loaded through findClass.
    The truth is that it tries to load with the getRessources methods and if it fails tries with the findClass/loadClass.
    To Fix the problem, I have simply overriden the getRessourceAsStream to do my magic and that was it.
    Thanks

  • How to get data from textfield from an other class

    Hello everyone,
    I have a problem with an application I am writing for school. I want to get the data from a textfield into an other class.
    I have two classes: KlantGui and KlantMenuGui
    Some Codes from KlantGui:
    public String klantNummer;
    //knr
    knr = new JTextField(10);
    p2.add(knr);
    //getValue
    public String getValue() {
         return knr.getText();
    //getKlantNummer
    public String getKlantNummer(){
         klantNummer = getValue();
         return klantNummer;
    }And this one is from KlantMenuGui:
    private KlantGui kg = new KlantGui();
    //This is where I want the data to display
    String klantnr = kg.getKlantNummer();
    p2.add(new JLabel (" Klantnr: "));
    tf4 = new JTextField (10);
    p2.add(tf4);
    tf4.setEditable(false);
    tf4.setText(klantnr);I don't know why but it seems like the getValue() doesn't sends the data. For example if I write klantNummer = "2" instead of klantNummer = getValue(); it does work and I see 2 in the other class.
    Thanks!

    Does knr ever get populated?
    From the code below, you create an instance of a KlantGui, but this will have no values set, then straight away call getValue, which returns "", which is correct since the textfield for the instance of KlantGui just created would be empty?

  • How to call amethod from some other application

    Hi,
    I have two web application running on the tomcat say [a] and . I need to call a method from [a] in [b] without adding the reference jar file of [a] in [b].
    How to do this?
    Please guide me..
    Thanks in advance.

    Hi,
    is not dependent on [a]. Two applications will be running on tomcat. There are some java classes in [a]. I need to invoke the method of those classes in [a] from [b] without replicating the classes of [a] in [b].
    Is there any way to do this?

  • How to invoke method dynamically?

    hai forum,
    Plz let me know how do we invoke a dynamically choosen method method[ i ] of a class file by passing parameter array, para[ ].The structure of my code is shown below.. How will i write a code to invoke the selected method method?Plz help.
    public void init()
    public void SelectClass_actionPerformed(ActionEvent e)
    //SELECT A METHOD method[ i ] DYNAMICALLY HERE
    private void executeButton1_mouseClicked(MouseEvent e) {
    //GET PARAMETERS para[ ] HERE.
    //METHOD SHOULD BE INVOKED HERE
    }//end of main class

    Often,a nicer way would be to create an interface like "Callable" with one single "doMagic()" method, and different classes implementing this interface, instead of one class with different methods. Then simply load the class by name, call newInstance(), cast to Callable and invoke doMagic(). Keeps you away from most of the reflection stuff.

  • How to call methods from within run()

    Seems like this must be a common question, but I cannot for the life of me, find the appropriate topic. So apologies ahead of time if this is a repeat.
    I have code like the following:
    public class MainClass implements Runnable {
    public static void main(String args[]) {
    Thread t = new Thread(new MainClass());
    t.start();
    public void run() {
    if (condition)
    doSomethingIntensive();
    else
    doSomethingElseIntensive();
    System.out.println("I want this to print ONLY AFTER the method call finishes, but I'm printed before either 'Intensive' method call completes.");
    private void doSomethingIntensive() {
    System.out.println("I'm never printed because run() ends before execution gets here.");
    return;
    private void doSomethingElseIntensive() {
    System.out.println("I'm never printed because run() ends before execution gets here.");
    return;
    }Question: how do you call methods from within run() and still have it be sequential execution? It seems that a method call within run() creates a new thread just for the method. BUT, this isn't true, because the Thread.currentThread().getName() names are the same instead run() and the "intensive" methods. So, it's not like I can pause one until the method completes because they're the same thread! (I've tried this.)
    So, moral of the story, is there no breaking down a thread's execution into methods? Does all your thread code have to be within the run() method, even if it's 1000 lines? Seems like this wouldn't be the case, but can't get it to work otherwise.
    Thanks all!!!

    I (think I) understand the basics.. what I'm confused
    about is whether the methods are synced on the class
    type or a class instance?The short answer is; the instance for non-static methods, and the class for static methods, although it would be more accurate to say against the instance of the Class for static methods.
    The locking associated with the "sychronized" keyword is all based around an entity called a "monitor". Whenever a thread wants to enter a synchronized method or block, if it doesn't already "own" the monitor, it will try to take it. If the monitor is owned by another thread, then the current thread will block until the other thread releases the monitor. Once the synchronized block is complete, the monitor is released by the thread that owns it.
    So your question boils down to; where does this monitor come from? Every instance of every Object has a monitor associated with it, and any synchronized method or synchonized block is going to take the monitor associated with the instance. The following:
      synchronized void myMethod() {...is equivalent to:
      void myMethod() {
        synchronized(this) {
      ...Keep in mind, though, that every Class has an instance too. You can call "this.getClass()" to get that instance, or you can get the instance for a specific class, say String, with "String.class". Whenever you declare a static method as synchronized, or put a synchronized block inside a static method, the monitor taken will be the one associated with the instance of the class in which the method was declared. In other words this:
      public class Foo {
        synchronized static void myMethod() {...is equivalent to:
      public class Foo{
        static void myMethod() {
          synchronized(Foo.class) {...The problem here is that the instance of the Foo class is being locked. If we declare a subclass of Foo, and then declare a synchronized static method in the subclass, it will lock on the subclass and not on Foo. This is OK, but you have to be aware of it. If you try to declare a static resource of some sort inside Foo, it's best to make it private instead of protected, because subclasses can't really lock on the parent class (well, at least, not without doing something ugly like "synchronized(Foo.class)", which isn't terribly maintainable).
    Doing something like "synchronized(this.getClass())" is a really bad idea. Each subclass is going to take a different monitor, so you can have as many threads in your synchronized block as you have subclasses, and I can't think of a time I'd want that.
    There's also another, equivalent aproach you can take, if this makes more sense to you:
      static final Object lock = new Object();
      void myMethod() {
        synchronized(lock) {
          // Stuff in here is synchronized against the lock's monitor
      }This will take the monitor of the instance referenced by "lock". Since lock is a static variable, only one thread at a time will be able to get into myMethod(), even if the threads are calling into different instances.

Maybe you are looking for

  • Our MacbookPro began running very slow a few days ago. I ran disk repair, permissions repair, and restored the OS from the Apple server. Kernal_Task appears to be using excessive CPU.

    EtreCheck version: 1.9.11 (43) - report generated June 15, 2014 at 7:45:12 AM CDT Hardware Information:           MacBook Pro - model: MacBookPro8,2           1 2 GHz Intel Core i7 CPU: 4 cores           4 GB RAM Video Information:           Intel HD

  • Will There be......?

    1.will there be an iphone either 3g or not.... that can be used for all countries without customize them.... or change its e.g. memory or data..... I ask because some say that in my countries the price are so $%#^^%$(don't get mad) high because of th

  • Java ME installation problem

    Hi, i am new to java me, but not to java in general. I am trying to install java me already   4 days and it still cannot be done. When i download java me sdk, usually the latest version, but i tried also previous versions, and i start the *.exe file

  • Cut copy and paste problems

    wondering if anyone else has noticed this yet. when copying it sometimes runs words together that weren't ran together before it was copied. example... in a very long sentence where there is a line break, it will run the word at the end of the line b

  • OTL (Additional Input Value) help greatly appreciated

    Hi there, I have a requirement where we wish to use OTL for a front end to a number of allowances which require the population of additional input values on the element. These could be for example miles travelled or the method of travel. Does anyone