-
Drawing with JPanel
Ok, wierd problem, I tried some really basic windowing without extending JPanel and JFrame:
Code:
import java.awt.*;
import javax.swing.*;
public class GraphTest {
public static void main(String[] args) {
JFrame frame = new JFrame("Test app");
JPanel panel = new JPanel();
initFrame(frame, panel);
}
private static void initPanel(JPanel p) {
p.setBackground(Color.white);
p.setFocusable(true);
p.setPreferredSize(new Dimension(500,500));
}
private static void drawSomething(JPanel p) {
Graphics g = p.getGraphics();
if(g == null) {
System.out.println("Can't get graphics");
return;
}
g.setColor(Color.black);
g.fillRect(200,200,50,100);
p.repaint();
}
private static void initFrame(JFrame f, JPanel p) {
f.getContentPane().add(p);
initPanel(p);
f.pack();
p.requestFocus();
drawSomething(p);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
All I get is a white window, without the black rectangle (drawn in drawSomething()). I got the Graphics context from JPanel, after drawing I called the repaint method, how come it doesn't show up?
-
You have seen the behaviour of active drawing versus passive drawing; it's the AWT EDT (Event Dispatch Thread) that decides when (part of) a component needs to be drawn. All the way down the call chain the paintComponent(Graphics g) method is called when the component needs to be repainted. The JPanel implementation doesn't do much more than repaint its entire area given a background color.
You have to extend that class and override the paintComponent( ... ) method to do some more interesting painting/drawing. This is passive drawing, the opposite of active drawing. So extend a JPanel class, override the paintComponent( ... ) method and you'll see the results.
Your rectangle was visible for just a moment. Then the JPanel's default paintComponent( ... ) ruined the show.
kind regards,
Jos
-
Ok, thanks a lot. I thought I could avoid extending my panel classes, now I know just do define a subclass of JPanel.