Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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.