Reputation: 951
It's been a long time since I did any drawing programs in Java and I can't get this one to work. The window stays empty even though there should be a filled oval there. Before the code was throwing a NullPonterException in the draw() function.
public class Map extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private Graphics graphics;
public static void main(String[] args) {
Map frame = new Map();
}
public Map() {
setTitle("Bugs");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 600);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel drawingPanel = new JPanel();
contentPane.add(drawingPanel, BorderLayout.CENTER);
this.setVisible(true);
graphics = drawingPanel.getGraphics();
draw(graphics);
}
public void draw(Graphics g){
Bug b = new Bug();
g.setColor(Color.RED);
g.fillOval(b.getPosX(), b.getPosY(), b.getRadius(), b.getRadius());
}
}
Upvotes: 0
Views: 84
Reputation: 2575
It is not enough to call draw(...)
only one time. This way the drawn content is lost immediately after your component is redrawn.
The correct approach would be as follows:
public class BugPanel extends JPanel {
private Bug bug;
public BugPanel(Bug b) {
bug = b;
}
@Override
public void paint(Graphics g) {
// draw your bug here
}
}
Then add this panel to the center region of your frame.
Upvotes: 1