Reputation: 3
Given these methods inside a class extending JPanel:
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
g.setColor(Color.BLACK);
}
public void drawLabels(LinkedList<Label> labelList) {
for (Label l : labelList) {
// drawString(l.getContent(), l.getX(), l.getY());
}
}
How would I go about accessing the Graphics element from paintComponent() inside drawLabels()? I have seen (numerous) remarks about not dealing with Graphics objects outside of the paintComponent() method, but I can't get my head around an alternate solution.
Any helpful suggestions would be appreciated.
Upvotes: 0
Views: 1147
Reputation: 324108
How would I go about accessing the Graphics element from paintComponent() inside drawLabels()?
You don't try to access the Graphics object directly.
You invoke the drawLabels()
method from inside the paintComponent()
method and then you can pass the Graphics object to the drawLabels() method:
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
g.setColor(Color.BLACK);
drawLabels(g, labelList);
}
public void drawLabels(Graphics g, LinkedList<Label> labelList) {
for (Label l : labelList) {
// drawString(l.getContent(), l.getX(), l.getY());
}
}
Upvotes: 2