I am new to Java and as an exercise I am trying to develop the following: 2 JPanels on a JFrame where 1 of the JPanels can be used for drawing. I started from an example from Daniweb from 2010 but can't seem to get a graphic context because the compiler gives me a null pointer exception. The program compiles and runs fine with the g.drawRect(100,0,150,50); commented out. The broader question is, how do I tell the program that I want to draw in a specific panel? My code is enclosed -- what am I doing wrong? Thanks, Bobonoinc
import java.awt.*;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.FlowLayout;
public class LinePaintDemo extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawLine(0, 0, getWidth(), getHeight());
g.drawLine(getWidth(), 0, 0, getHeight());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setSize(300,300);
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contPanel = new JPanel();
contPanel.setBackground(Color.red);
contPanel.setPreferredSize(new Dimension(50, frame.getSize().height));
frame.add(contPanel);
LinePaintDemo canvase = new LinePaintDemo();
canvase.setBackground(Color.green);
canvase.setPreferredSize(new Dimension(200, frame.getSize().height));
frame.add(canvase);
Graphics g = canvase.getGraphics();
// g.drawRect(100,0,150,50);
frame.setVisible(true);
}
});
}
}