Java Difficulty

Started by
3 comments, last by guyver23 18 years, 7 months ago
Hi! I am in the processs of learning Java--of course with the intent of making games, and my first basic graphics demo is already causing problems. When I make a jar out of the code, the window displays, but the background is gray. Only when I maximize it or change its size does the background change color and the rectangle display. If I cover the window with another (like opening another program), the color reverts and the display won't be right until I move it again! Can someone please tell me what is wrong with the code? Thanks!
[source lang = "java"]

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame
{
    private Insets limit; // used to determine window boundries 
    private Container c; // used to display stuff
    private Color happyRect;
    
    public Main()
    {
        super("Color Test");
        
        c = getContentPane();
       
        setSize(300,300);
        c.setBackground(Color.blue);
        setVisible(true);
    }
    
    public void paint(Graphics g)
    {
        limit = c.getInsets();
        
        g.setColor(Color.orange);
        g.fillRect(10 + limit.left, 10 + limit.top, 30, 30);
    }
    
    public static void main(String args[])
    {
        Main app = new Main();
        
        app.addWindowListener( new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }
}


Advertisement
If I read this correctly, try using repaint().
I have an excellent Tutorial that I have found.

Java Invaders

It goes from your first window, to the fully fledged space invaders clone. It covers double buffering and other things that are needed in basic game design within Java.

I Hope this helps.

H_o_p_s
BRING BACK THE BLACK (or at least something darker)
Use the Java Invaders link. It gets to your issue very quickly. Basically the idea is you want to draw to a Canvas rather than a JFrame. You need a custom Canvas subclass, either instead of or in addition to your JFrame subclass.

The Space Invaders tutorial is a real gem. Thank you, H_o_p_s, for pointing it out.
Thanks so much everyone! =)

This topic is closed to new replies.

Advertisement