I have a question regarding Graphics in Java. Maybe it is a basic question. Below you can see my Code to create a Graphics object with my panel in a JFrame. I would like to create a graphics object in the constructor.(If i create the graphics object in a button it works) If I start the application I get immediately a nullpointer exception because of g.setColor(Color.RED);
But I don't understand why I get this exception. I have debugged the programm and the panel is created before I use the .. = panel.getGraphics(); command. So normally my Graphics object should be generated correctly and not null. So it should not be a problem to set a Color. Could you please explain me why I get this exception?
public class G2DTest extends JFrame {
private JPanel contentPane;
private JPanel panel;
Graphics g;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
G2DTest frame = new G2DTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public G2DTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 796, 810);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(80, 87, 309, 234);
contentPane.add(panel);
JRadioButton rdbtnRot = new JRadioButton("rot");
rdbtnRot.setBounds(438, 183, 251, 41);
contentPane.add(rdbtnRot);
g = panel.getGraphics();
g.setColor(Color.RED);
}