java graphics颜色,Java - 更改使用Graphics2D创建的某些正方形的颜色

I just want to create a simple game with 100 x 100 square, each square is 5 pixels.

I created a class:

public class Draw extends JComponent{

private List recList = new ArrayList();

public void paint(Graphics g) {

//THIS TO SET (0,0) PANEL START AT BOTTOM LEFT

Graphics2D g2 = (Graphics2D)g;

AffineTransform at = g2.getTransform();

at.translate(0, getHeight());

at.scale(1, -1);

g2.setTransform(at);

//THIS TO DRAW ALL THE SQUARES

for (int i = 0;i<100;i++){

for (int j=0;j<100;j++){

g2.setColor(Color.red);

g2.drawRect(5*i, 5*j, 5, 5);

recList.add(g2); //Store each square to the list to change the color

}

}

}

}

Then I just drag it to the design windows of netbeans and the squares are painted, looks good...

But it seems like I made a wrong move. At the first time I wanted to get a specific square from the list using their location, but the Graphic2d doesn't have any method to get the location (x and y) or to change the color.

I don't know if there is any other way I can make it come true?

PS: One more thing, can I set the location of each square to its center?

解决方案

You could create your own Tile class, which stores info such as x, y, width, height, and color. Each Tile object could also be in charge of painting itself:

class Tile {

private int x, y, width, height;

private Color color;

public Tile(int x, int y, int width, int height, Color color) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

this.color = color;

}

public void paint(Graphics g) {

g.setColor(color);

g.fillRect(x, y, width, height);

}

}

Create the tiles before-hand:

List tiles = ...;

void createTiles() {

for(int x = 0; x < 100; x++) {

for(int y = 0; y < 100; y++) {

Color color = ...; //choose color

int size = 5;

int tileX = x * size;

int tileY = y * size;

tiles.add(new Tile(tileX, tileY, size, size, color));

}

}

}

Then render by passing the graphics object to them in the paint method:

void paint(Graphics g) {

tiles.forEach(tile -> tile.paint(g));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值