Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Ian Z
Ian Z
14,584 Points

How do you call the methods of a class that was created in another class, from another class? Java, Swing, Android

So i am trying to create some animated game play text for my breakout game in Java Swing gui.
Heres whats should happen- Everytime a brick is hit its points will Slam onto the screen, pause for .25 seconds and then fade up into nothing. To do this i have a timer inside a method inside a class called AlertText.

When the brick is hit in the class GameLogic, a new AlertText is created and its timers start running. Now in the Game Class i have the paint class.
So how do i call upon the specific instances of AlertText that were created in GameLogic to use the setter and getter methods to set my g.drawString in Game class.

I got it to work with Global variables for one style of brick so i know animation is working, but i would need 100+ global variables to do every kind of brick...

1 Answer

Taha Abbasi
Taha Abbasi
12,865 Points

Hi!

If the classes are in the same package, then you can just initialize a new instance of an object from the class you want to call the method from in the class you want to call the method in e.g.

if you want to call methods from AlertText class in Game Class, here is the code you can implement in Game Class:

Assuming your classes are not in the same package, you will need to import the other class like:

import com.ian.AlertText;

you don't have to do the above import if the classes are in the same package

Now you can initialize an instance of the AlertText class:

AlertText alertText = new AlertText();

After doing the above you should be able to call methods on the variable alertText:

alertText.getSomething();
alertText.setSomething();

P.S. if you provide snippets of your code here, you will get more accurate answers :)

Hope this helps.