Hello Everyone,

I understand this is a basic problem, with a simple solution, but I cannot find a way to fix it.

I'm trying to add a Jpanel to a JFrame and when I do the following.

g.drawString("HELLO", 500, 0);

The string is not seen on screen now if I do

g.drawString("HELLO", 500, 5);

This can be half-seen at the top, and perfectly if I make the y position 10 pixels. So I guess it has an offset of 10pixels (I don't know if this is the right word).

The Frame class its...

package Graphics;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Frame extends JFrame
{
    private final int WIDTH = 800, HEIGHT = 600;
    private final String TITLE = "Angry Birds Replica";
    private final Panel mainPanel;

    public Frame()
    {
        setTitle(TITLE);

        setMinimumSize(new Dimension(WIDTH, HEIGHT));
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setMaximumSize(new Dimension(WIDTH, HEIGHT));

        mainPanel = new Panel(WIDTH, HEIGHT);
        add(mainPanel, BorderLayout.CENTER);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }

}

The Panel class its...
package Graphics;

package Graphics;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Panel extends JPanel
{
    private Color backgroundColor = Color.black;

    public Panel(int WIDTH, int HEIGHT)
    {
    }

    public void paint(Graphics g)
    {
        super.paint(g);
        setBackground(backgroundColor);
        g.setColor(Color.white);
        g.drawString("HELLO", 500, 10);

    }
}

I would appreciate if anyone could point me in the right direction. I'm still searching for an answer but I lack the proper use of words to find this.

The place you should look is here: http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawString%28java.lang.String,%20int,%20int%29

That is the Javadoc for the the drawString method, and it says that the (x,y) point that you give it is "the baseline of the leftmost character." You seem to expect the (x,y) to be the top corner of the leftmost character, but making text readable is easier when you work with baselines. It lines up better that way.

You can use getFontMetrics to discover how far the baseline is below the top of the text.

You should always look at the Javadoc first, even before you have a problem. It's not safe to call a method if you haven't read the Javadoc for that method.

You should always look at the Javadoc first, even before you have a problem

Thank You. I rarely use the javadocs but with this experience that will change.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.