1

I got 2 classes:
- 1st. makes a frame (JFrame) and adds a panel (JPanel) on it
- second one makes the panel and draws a rectangle on it (at least i thought it would)

this is the first class

class Frame {
JFrame frame;
Panel panel;

void draw() {
    frame = new JFrame ("qwertz");
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.setSize(300,200);

    panel = new Panel();
    panel.setLayout(null);
    panel.paint();
    frame.add(panel);
    }}

and the second

class Panel extends JPanel {
void paint() {
    Graphics g = getGraphics();

    g.drawRect(50,50,90,70);
}}

when i call the draw() method from the first class it throws this exception at me:

java.lang.NullPointerException  
          at Panel.paint(Panel.java:8) ((  g.drawRect(50,50,90,70);  ))
          at Frame.draw(Frame.java:15) ((  panel.paint();            ))
2

3 Answers 3

2

That's not how you're supposed to paint. To paint a component, override the paintComponent(Graphics g) method of the JPanel then call repaint();

class MyPanel extends JPanel {
    @Override // <-- this makes a compiler error if you typod the method name
    public void paintComponent(Graphics g) {
        g.drawRect(50,50,90,70);
    }
}

and

panel = new MyPanel();
panel.setLayout(null);
panel.repaint(); // <<---- Look here! It says repaint() not paint()
frame.add(panel);

Also, if all you have to do is paint on this panel, I'd consider using a plain-old Component, and overriding paint(Graphics g) instead of paintComponent(Graphics g). paintComponent(Graphics g) is exclusively for swing components.

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

2 Comments

what exactly happens, when you override the paintComponent(Graphics g) method and don't add super.paintComponent(Graphics g) to the first line of the method implementation ?
It won't do any of the other painting that the class would normally do, had you not overwritten that method, such as painting childred added to a container.
1

instead of implementing the paint method, you should implement the paintComponent(Graphics g) method. This way, the graphics object you have is valid.

http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)

Comments

0

You are trying to draw the panel before it is added to the Frame. Try to move frame.paint(); below frame.add(panel);. Additionally if you are using Swing you should use JPanel instead of Panel.

Comments

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.