0

I'm trying to make a test window with some text on it, when I run my code, it doesn't draw the string. I specified the color for it. Can anybody help me with this?

Here what it draws

import javax.swing.*;
import java.awt.*;

class Main
{
    public static void main(String[] args) {
        DrawFrame f = new DrawFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}
class DrawFrame extends JFrame
 {
    public DrawFrame(){
        setTitle("For Aylin");
        setSize(1280,720);

        DrawPanel panel = new DrawPanel();
        Container cp = getContentPane();
        cp.add(panel);
    }
}

class DrawPanel extends JPanel
{
    public void paintComponents(Graphics g)
    {
        super.paintComponents(g);
        g.setColor(Color.darkGray);
        g.drawString("Hi", 100, 10);
    }
}

1 Answer 1

3

You should override the JPanel's paintComponent method not its paintComponents method as they are for two very different purposes. The first paints the component itself (what you want) while the second gets the child components held by this parent to paint themselves.

Also remember to change the super call so that it matches, and to use the @Override annotation above the method.

Sign up to request clarification or add additional context in comments.

Comments

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.