Coderman69
Coderman69

Reputation: 67

Graphics.drawString() doesnt draw anything on the screen

I'm trying to draw a string with the Graphics.drawString(). But for some reason nothing shows up on the screen. Drawing a rectangle for example works but drawString() doesn't.

Here's my code:

public class Main extends JFrame {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        this.setSize(350, 500);
        this.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
    
        //Nothing is drawn on the screen.
        g.setColor(Color.RED);
        g.setFont(new Font("Arial", Font.BOLD, 25));
        g.drawString("Hello", 10, 10);
    }
}

Upvotes: 1

Views: 138

Answers (2)

Instead of drawing on the JFrame, which is does not draw it to the exact coordinates, make your main class a child of JPanel by using this code:

public class Main extends JPanel {

    public static void main(String[] args) {
        new Main();
    }
    
    JFrame frame = new JFrame();
    
    public Main() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        frame.pack();
        frame.setSize(350, 500);
        frame.setVisible(true);
    }
}

Now add your paint method

@Override
    public void paint(Graphics g) {
        super.paint(g);
    
        g.setColor(Color.RED);
        g.setFont(new Font("Arial", Font.BOLD, 25));
        g.drawString("Hello", 10, 10);
    }

Upvotes: 0

Programmer
Programmer

Reputation: 813

When using Graphics class to draw anything to the Component, you should know one important thing:

While drawRect(int x, int y, int width, int height) method the x and y are the top-left corner, in the drawString(String s, int x, int y) the x and y are the bottom-left corner.

In addition, when you draw anything in a JFrame, the position start on the top-left corner on the title of the JFrame, so the first paintable pixel is in point (~8, ~28), this is different in every operating-system.

Upvotes: 1

Related Questions