Computer Science Canada

Graphics in Java

Author:  np_123 [ Thu Oct 30, 2014 5:09 pm ]
Post subject:  Graphics in Java

Can graphics only be drawn from inside the paint() or paintComponent() method? Is there a difference between paint() and paintComponent()?

For example, I have working code that draws a checkerboard. But if I want to go ahead and draw pieces on it, then move the pieces, how would I do that without redrawing the entire thing each time? because as far as i've been able to figure out, the only way to draw stuff is from the paint() method, and it draws everything in there all at once.

Java:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Checkerboard extends JPanel {
       
        public static void main(String[] args) {

                createWindow ();
   
   
   }

        public static void createWindow (){
               
              //Creates the window and makes it visible
              JFrame window = new JFrame();
              window.setSize(695, 720);
              window.add(new Checkerboard());
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              window.setVisible(true);
               
        }

   public void paint (Graphics g) {
          
             for (int x=0; x < 8; x++){
               for (int y =0; y < 8; y++) {
                
                 if ((y % 2 == 0 && x % 2 == 0) || (y % 2 == 1 && x % 2 == 1)) {         
                   g.setColor (Color.BLACK);
                   g.fillRect (x * 85, y * 85, 85, 85);
                 }
                   else {           
                   g.setColor (Color.RED);
                   g.fillRect (x * 85, y * 85,  85, 85);             
                   }       
               }       
             }

          
   }   
   
}


: