jaynp
jaynp

Reputation: 3325

How can I draw things using this Java GUI API?

My instructor has defined this API for graphics.

It's very simple but I've spent an hour or two now trying to figure out how to make simple Graphics manipulations show up.

So I have a class T which extends TopLevel and it is my main frame. I also have a Pad P which extends Pad and here's the body of its paintComponent method:

@Override
protected void paintComponent(Graphics2D g) {
    super.paintComponent(g);
    g.drawString("Hello", 0, 0);
    g.fill(new Rectangle(5, 5));
    repaint(); //(Probably don't need)
}

I then call T.add(P), (I also do T.addButton(..) and T.display(true). When I run the application I see an empty canvas with the button I've created.

Any help is appreciated.

Upvotes: 0

Views: 452

Answers (2)

nicephotog
nicephotog

Reputation: 11

T.setVisible(true); // after construction

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347314

Drawing text is not as simple as you think.

The y position represents the font's base line (the point where most text sits. There is also a decent line, where characters that sit below the base line will extended to (characters like 'g' and 'p').

The font also has a ascent. This is the "height" of a typically character above the base line (excluding, obviously, the descent)

enter image description here

Image from Measuring Text

In order to paint the text properly, you must ALWAYS add the ascent to the y position...

FontMetrics fm = g.getFontMetrics();
g.drawString("Hello", 0, fm.getAscent());

You can also lose the repaint call, this will cause the repaint manager to (eventally) call the paint method of you component, over and over and over...again...

In Swing, Graphics is typically set up so that the color is the components foreground color. You may want to try changing the color just to be sure.

Try using something like g.setColor(Color.RED); before trying to paint anything.

Upvotes: 2

Related Questions