I'm not able to see content on JFrame ,when JFrame shows up.

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
public class GraphicUse extends JPanel
{
public void PaintComponent(Graphics gr)
{   
    super.paintComponents(gr);
    this.setBackground(Color.BLUE);
    gr.setColor(Color.WHITE);
    gr.fillRect(50, 50, 100, 100);
    gr.setColor(new Color(139,38,190));
    gr.fillRect(50, 70, 100, 100);
    gr.setColor(Color.RED);
    gr.drawString("This is a new String", 50, 90);  
}

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

}

And displaying it in another class which extends Frame

JFrame newframe = new JFrame("Color Frame");
             newframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         
             GraphicUse gu = new GraphicUse();           
             newframe.add(gu);
             newframe.setSize(250,300);
             newframe.setVisible(true);

This is why the @Overrride annotation was invented!
If you prefix that annotation to your PaintComponent method you will discover that it doesn't override anything. Here's a hint: Java names are case sensitive.

The method PaintComponent(Graphics) of type GraphicUse must override or implement a supertype method

Exactly. It's not overriding because the superclass does not have a method called PaintComponent. Here's a hint: Java names are case sensitive.

+1 for Java Naming Conventions

  • and very important details don't to call, never super.paintComponents(gr); but super.paintComponent(gr);

  • paintComponents required little bit more effort and knowledge than simple paintComponent, then is easier to override paintChildren

__________________________

  • override getPreferredSize for public class GraphicUse extends JPanel, don't forget to add @Overrride annotation too, then all sizing is quite useless and contraproductive, use frame.pack() instead of code line newframe.setSize(250,300);

+1 for spotting the "s"

Here's an updated hint: Java names are case sensitive, and "Component" is not the same as "Components"

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.