Reputation: 459
I'm currently making a game in Java with AWT. The main class extends Frame, and I've been using it to draw the graphics using .getGraphics() and .drawRect(). This has been working fine, except that when I add components like labels to the frame it stops rendering the graphics and only displays the components.
Upvotes: 0
Views: 624
Reputation: 208984
getGraphics()
to paint. That is not the proper way.paintComponent(Graphics g)
method of the JPanel. Do all your painting in this method, use the implicitly passed Graphics context. You never have to actually call paintComponent
as it will be implicitly called for you.paintComponent
, you're going to want to override paint
, as AWT components don't have a paintComponent
method. But I strongly urge you to use Swingpublic class SimplePaint {
public SimplePaint() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawPanel extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(50, 50, 150, 150);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SimplePaint();
}
});
}
}
Upvotes: 2