java 像素 颜色_在Java中获取像素的颜色

我会存储一个Rectangle数组,并在点击时查找哪一个包含该点。

ydLfe.png

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ChessBoard extends JPanel {

public static final int SIZE = 400;

public static final int COUNT = 8;

public static final int TILE_SIZE = SIZE / COUNT;

public static final Color RED = Color.RED;

public static final Color BLUE = Color.BLUE;

public static Tile[][] tiles;

static {

ChessBoard c = new ChessBoard();

tiles = new Tile[COUNT][COUNT];

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

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

tiles[i][j] = c.new Tile(i * TILE_SIZE, j * TILE_SIZE,

TILE_SIZE, TILE_SIZE);

}

}

}

public static void main(String[] args) {

JFrame f = new JFrame();

ChessBoard c = new ChessBoard();

f.setTitle("Chessboard Tile Click");

f.setContentPane(c);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

public ChessBoard() {

setPreferredSize(new Dimension(SIZE, SIZE));

this.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

Point p = e.getPoint();

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

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

Rectangle tile = tiles[i][j];

if (tile.contains(p)) {

JOptionPane.showMessageDialog(null,

String.format("Clicked Tile: %s", tile));

break;

}

}

}

}

});

}

@Override

protected void paintComponent(Graphics g) {

boolean flip = false;

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

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

Rectangle tile = tiles[i][j];

g.setColor((flip = !flip) ? BLUE : RED);

g.fillRect(tile.x, tile.y, TILE_SIZE, TILE_SIZE);

g.setColor(Color.WHITE);

g.drawString(tile.toString(), tile.x + (TILE_SIZE / 2) - 8,

tile.y + (TILE_SIZE / 2) + 6);

}

flip = !flip;

}

}

private class Tile extends Rectangle {

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

super(x, y, width, height);

}

@Override

public String toString() {

return String.format("%c%d", 'A' + x / TILE_SIZE, COUNT - y

/ TILE_SIZE);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值