d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > [java] Need Help With Painting Methods
Add Reply New Topic New Poll
Member
Posts: 4,841
Joined: Jan 16 2008
Gold: 0.00
May 15 2013 12:02pm
I've spent all afternoon trying to get the following done:

I want to write some static methods (within their own class) which take a JFrame as paramter.
Then the method paints something (a simple shape, like a circle) on the frame when I call it.

Could anybody help me get started, please?
Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
May 15 2013 01:03pm
Took me a while to figure out you have to Override paint(Graphics g) for your JFrame. I'm guessing you had a similar problem.

Code
import java.awt.Graphics;
import javax.swing.JFrame;

public class Test {
 public static void main( String[] a ) {
   new Test( );
 }

 public Test( ) {
   JFrame jFrame = new JFrame( ) {
     public void paint( Graphics g ) {
     }
   };
   jFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   jFrame.setSize( 400, 400 );
   jFrame.setVisible( true );
   fillOval( jFrame );
 }

 public static void fillOval( JFrame jFrame ) {
   jFrame.getGraphics( ).fillOval( 200, 200, 50, 50 );
 }

}


This post was edited by labatymo on May 15 2013 01:14pm
Member
Posts: 4,841
Joined: Jan 16 2008
Gold: 0.00
May 15 2013 04:33pm
Genius :)

As far as I understood, repaint(), which is called all the time when the frame is active, is calling paint(), which is overpainting my self-drawn shape from the paintclass-method. That's why you override the frame's paint-method to do nothing.
Member
Posts: 4,841
Joined: Jan 16 2008
Gold: 0.00
May 15 2013 06:06pm
Next problem: in my painter methods, frame.getGraphics().setColor(Color.red) seems to get ignored. I can only paint in black.

edit: apparently you need a new graphics object (note the .create()):

Code
public static void fillSq(JFrame frame, Point pt, Color col) { //Point is center
       Graphics gr=frame.getGraphics().create();
       gr.setColor(col);    
       int centerx=(int)pt.getX();
       int centery=(int)pt.getY();
       gr.fillRect(centerx-Grid.SIDE/2, centery-Grid.SIDE/2, Grid.SIDE, Grid.SIDE);
   }


dont really get why, though

This post was edited by tt_toby on May 15 2013 06:30pm
Member
Posts: 22,238
Joined: Aug 28 2007
Gold: 0.00
May 29 2013 02:30pm
Quote (tt_toby @ 16 May 2013 01:06)
Next problem: in my painter methods, frame.getGraphics().setColor(Color.red) seems to get ignored. I can only paint in black.


mwe would help
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll