Problems using graphics with panels in Java Swing Library

Hi everyone, I am trying to run the following program but I am getting a NullPointerException. I am new to Java swing library so I can do something very dumb. Anyway, these are my two classes I'm currently playing in and all I want to do is draw a damn circle (I don't want to draw a gallow with an executioner after all).

package hangman2;

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

public class Hangman2 extends JFrame{
    private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
    private Gallow gallow = new Gallow();

    public Hangman2() {

        setLayout(alphabetLayout);

        setSize(1000,500);
        setVisible( true );

    }

    public static void main( String args[] ) {   
     Hangman2 application = new Hangman2();
     application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }
}


package hangman2;

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

public class Gallow extends JPanel {
    private Graphics g;

    public Gallow(){
        g.fillOval(10, 20, 40, 25);       
    }
}

      

A NullPointerException is included in the g.fillOval line.

Thanks in advance,

Tomek

0


source to share


2 answers


You get NPE because it is g

not installed, which is why it is null

. Also, you don't have to draw the drawing in the constructor. Overload paintComponent(Graphics g)

instead.

public class Gallow extends JPanel {
    public paintComponent(Graphics g){
        g.fillOval(10, 20, 40, 25);       
    }
}

      



I'll also take a look at BufferedImage .

+4


source


A few things: don't forget to add the panel to JFrame

. And override the method paint()

JPanel

for your custom coloring. You don't need to declare a Graphics object, as the drawing method JPanel

will reference one anyway.



package hangman2;

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

public class Hangman2 extends JFrame{
    private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
    private Gallow gallow = new Gallow();

    public Hangman2() {

        setLayout(alphabetLayout);
        add(gallow, BorderLayout.CENTER);//here
        setSize(1000,500);
        setVisible( true );

    }

    public static void main( String args[] ) {   
        Hangman2 application = new Hangman2();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }
}


package hangman2;

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

public class Gallow extends JPanel {

    public Gallow(){
        super();
    }

    public void paint(Graphics g){
        g.fillOval(10, 20, 40, 25);       
    }
}

      

0


source







All Articles