Reputation: 4839
Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).
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);
}
}
The NullPointerException comes in at the g.fillOval line.
Thanks in advance,
Tomek
Upvotes: 0
Views: 3945
Reputation: 103145
A couple of things: Don't forget to add the panel to the JFrame
. And override the paint()
method of JPanel
for your custom painting. You do not need to declare a Graphics object since the JPanel
's paint method will have a reference to one in any case.
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);
}
}
Upvotes: 0
Reputation: 61434
You're getting NPE because g
is not set, therefore, it's null
. Furthermore, you shouldn't be doing 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'd also look into BufferedImage.
Upvotes: 4