0
g.drawString(p2.getName(), 800 - FontMetrics.stringWidth(p2.getName()), 40);

That line results in the error " Cannot make a static reference to the non-static method stringWidth(String) from the type FontMetrics.

The getName() method is defined in the player class, and p2 is an instance of that class, so I don't see how p2.getName() is a static reference.

4 Answers 4

3

You need to use an instance of FontMetrics. You can obtain one from the Graphics object:

g.drawString(p2.getName(), 800 - g.getfontMetrics().stringWidth(p2.getName()), 40);
Sign up to request clarification or add additional context in comments.

Comments

2

Because it is not - the static reference is stringWidth.

FontMetrics.stringWidth is an instance method. The error message is:

Cannot make a static reference to the non-static method stringWidth(String) from the type FontMetrics

2 Comments

So how would you fix this?
@OliverBennett that depends - you need to obtain a FontMetrics instance and call it as fontMetrics.stringWidth(p2.getName()), fontMetrics is the variable name.
1

The stringWidth() method is not a static method and needs an instance of FontMetrics to access it.

You are accessing it as a static method, so it gives you the error.

Comments

1
g.getFontMetrics.stringWidth("your string")

1 Comment

You need getFontMetrics() instead of getFontMetrics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.