Luke Honeyball
Luke Honeyball

Reputation: 11

Java Graphics Are Not Displaying on Application

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.

Upvotes: 0

Views: 88

Answers (1)

camickr
camickr

Reputation: 324098

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.

Upvotes: 3

Related Questions