JamEngulfer
JamEngulfer

Reputation: 747

write a variable with drawstring()

I'm having some issues with the graphics in my program. I want to drawstring() to draw a variable on the screen, however, the variable is given from another class.

An 'outline' of what I have is this:

public void paint(Graphics g){
    g.drawString(text, sPosX, sPosY);
}

That is my paint method. I want another class to run it, whilst passing a text variable to say what the drawstring will say.

I'm unsure on how to do this, as I can't do something like gui.paint(null, data) (gui is the name of the class) because even if I add (String text) to the paint() method, I get errors.

If you could help that would be greatly appreciated. Thanks!

Upvotes: 0

Views: 2499

Answers (1)

Greg Kopff
Greg Kopff

Reputation: 16585

Give your GUI class a field, with a setter, and have your paint method reference the field.

public class GUI extends Component
{
  private String text;

  public void setText(String text)
  {
    this.text = text;
  }

  public void paint(Graphics g)
  {
    g.drawString(this.text, sPosX, sPosY);
  }
}

In your other class:

gui.setText("Now is the time for all good men");

Upvotes: 3

Related Questions