Lets say I make a simple graphical application. It has two classes, the main class and a second class called "panel" that extends JPanel. The main class is just a JFrame that contains the JPanel. Here are its contents:
public static Panel panel = new Panel();
public static void main(String[] args) {
JPanel p = new Panel();
JFrame fr = new JFrame();
fr.setSize(600, 600);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLocationRelativeTo(null);
fr.setVisible(true);
fr.add(p);
while (true) {
fr.repaint();
if (panel.test) panel.g2d.drawRect(30, 30, 40, 40);
}
}
The second class uses Graphics2D to create the contents of the JPanel. It also has variables that are changed within the paintComponent() method. Here are its contents:
Graphics2D g2d;
boolean test = false;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2d = (Graphics2D) g;
test = true;
g2d.setColor(Color.RED);
g2d.drawRect(10, 10, 20, 20);
}
However, here's the problem: neither test
nor g2g
appear to change after the paintComponent() method has executed. The code in the while loop of the main method never ends up drawing a rectangle though the paintComponent() method draws its rectangle fine. In the main method, test
and g2g
appear to always be false
and null
respectively. What am I missing here? Is there anyway to use the graphics2D outside the paintComponent() method?
Get rid of that while (true)
block, it's not needed and it's harmful as it risks stomping on your GUI thread. Instead add your JPanel before calling setVisible(true)
on your JFrame.
Also, creating a Graphics2D field and trying to draw with it outside of paintComponent is inviting a NullPointerException. Understand that you don't have full control over Swing Graphics and should not try to extract a Graphics object or do drawing that way. You will want to read the Swing Graphics tutorial to learn how to properly draw with Swing components.
So to answer,
Is there anyway to use the graphics2D outside the paintComponent() method?
No. You can get around this by drawing with a BufferedImage's Graphics object, but then you still need to draw the BufferedImage to your JPanel or JComponent's paintComponent method.