Java Graphics Disappear


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Java Graphics Disappear

  1. #1
    Join Date
    May 2006
    Posts
    10

    Java Graphics Disappear

    Hi all,

    I am trying to place some simple graphics on a JFrame window using the Graphics2D class. The graphics rarely remain on the window more than 1/10 of a second. Here is the body of the main method:

    JFrame win;
    Container contentPane;
    Graphics2D g;

    win = new JFrame();
    win.setSize(300, 200);
    win.setLocation(100, 100);
    win.setVisible(true);

    contentPane = win.getContentPane();

    g = (Graphics2D)contentPane.getGraphics();
    g.setColor(Color.BLUE);
    g.drawRect(50, 50, 100, 30);

    g.setColor(Color.RED);
    g.fillRect(175, 50, 100, 30);

    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    I also tried outputting a line instead of rectangles. I am using the Eclipse IDE; but I have also tried it with the command prompt, which worked correctly maybe half of the time, better than with Eclipse. I've also copied code directly from a textbook, and it did not work.

    Thanks a lot.

    Davy

  2. #2
    Join Date
    Oct 2005
    Posts
    107
    you should override the JFrames paint method. The way your doing it, the graphics will be lost when a repaint is needed. (move the window, resize the window, etc.)

    Code:
    win = new JFrame(){
    public void paint(Graphics g){
    g.setColor(Color.BLUE);
    g.drawRect(50, 50, 100, 30);
    
    g.setColor(Color.RED);
    g.fillRect(175, 50, 100, 30);
    
    }
    }
    can't remember if it's paint or paintComponent. Actually not even sure if it's right to do the painting on a JFrame...I've always done it with a JPanel.

  3. #3
    Join Date
    May 2006
    Posts
    10
    Thanks, Joe. I tried what you said to do, and it works perfectly now (without adding a JPanel). Thanks a lot!

    Davy

Similar Threads

  1. Replies: 2
    Last Post: 06-14-2006, 03:16 PM
  2. Java vs. .Net. A questionnaire
    By Basil in forum .NET
    Replies: 1
    Last Post: 05-13-2005, 06:46 AM
  3. learning c# very confusing.
    By Mike Tsakiris in forum .NET
    Replies: 11
    Last Post: 10-04-2002, 05:32 PM
  4. Re: VB vs. Visual Age for Java
    By JJ in forum Enterprise
    Replies: 1
    Last Post: 07-06-2000, 04:50 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center