1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
package swing.tests;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Checker extends JComponent {
private Color darkColor = new Color(127,43,15);
private Color lightColor = new Color(220,157,90);
private int cellLineNumber = 8;
private int cellColNumber = 8;
private BufferedImage pawn;
public Checker() {
try {
pawn = ImageIO.read(this.getClass().getResource("/pawn.png"));
} catch (IOException e) {
// TODO Bloc catch auto-généré
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
int width = getWidth();
int heigth = getHeight();
int cellWidth = width/cellColNumber;
int cellHeight = heigth/cellLineNumber;
for(int i = 0; i<cellLineNumber; i++) {
for(int j = 0; j<cellColNumber; j++) {
if((i+j)%2==0) {
g.setColor(lightColor);
} else {
g.setColor(darkColor);
}
g.fillRect(j * cellWidth, i* cellHeight, cellWidth, cellHeight);
if(i <2 || i > cellLineNumber -3) {
drawPiece(g, i, j, pawn);
}
}
}
}
private void drawPiece(Graphics g, int line, int col, BufferedImage im) {
int width = getWidth();
int heigth = getHeight();
int cellWidth = width/cellColNumber;
int cellHeight = heigth/cellLineNumber;
int imageWidth = im.getWidth();
int imageHeight = im.getHeight();
int pieceX = col * cellWidth + cellWidth/2 - imageWidth/2;
int pieceY = line * cellHeight + cellHeight/2 - imageHeight/2;
g.drawImage(im,pieceX,pieceY,null);
}
/**
* @param args
*/
public static void main(String[] args) {
Checker c = new Checker();
JFrame f = new JFrame();
f.add(c);
f.setSize(400,400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
}
} |
Partager