0

This is the code of a recent java application that I created. It was created in Eclipse IDE and there were no errors found. I am wondering my mistake... Just check the below code for errors.

The First Class:

import javax.swing.*;
public class GraphicsGo extends JFrame{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        System.out.println("Noice");
        JFrame jf = new JFrame();
        JPanel pnl = new JPanel();
        jf.add(pnl);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        graphics gr = new graphics();
        jf.setSize(400, 250);
        pnl.add(gr);
        jf.setVisible(true);
    }
}

The Second Class:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class graphics extends JPanel{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void PaintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.red);
        g.setColor(Color.blue);
        g.drawRect(0, 0, 2, 2);
        setVisible(true);
    }
}

The window I think I did everything right.

The classes are two different files.

0

1 Answer 1

3

Many issues:

  1. Method names should NOT start with an upper case character. The method to override should be paintComponent(...).

  2. Class names SHOULD start with an upper case character. Rename your "graphics" class to something more meaningful. Learn Java naming conventions and follow them to avoid confusion and mistakes like this.

  3. a painting method should NOT change the state of the class. Don't invoke setBackground(). That method should be invoked in the constructor or on the instance variable when the object is created.

  4. When doing custom painting you need to override the getPreferredSize() of the component. Currently your custom component doesn't have a reasonable preferred size so the layout manager can't set its size/location effectively.

See the Swing tutorial on Custom Painting for working examples showing how to better structure your code to implement all the above suggestions.

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

2 Comments

Thanks so much. Its worked! I just had to change the PaintComponent() to paintComponent()!
@LukeHoneyball, I just had to change... - no, that is NOT the only change to make. It may appear to work, but it will NOT work if you change the painting code. For example change the width/height of the rectangle to (200, 200) to see it doesn't work. Learn how to do painting properly and learn how to structure your code properly.

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.