- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我和一个 friend 正在为我们的 AP 计算机科学类(class)使用 Java 从头开始制作一个国际象棋游戏,我们需要在释放鼠标后获取最终方 block 的坐标。 .getX()
和 .getY()
为我们提供了精确的坐标,但我们需要网格坐标。就像 5,4 或 3,2(在国际象棋中,这将是 e4 或 c2)。定义类都工作正常,我们只需要这部分:
System.out.print(e.getX()+" "+e.getY());
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
}
else {
Container parent = (Container)c;
parent.add( chessPiece );
}
chessPiece.setVisible(true);
}
完整的实现类如下。提前致谢!
package Boards;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChessGame extends JFrame implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;//Serial ID for unique chess games
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
public ChessGame(){
Board newGame = new Board();//Instantiate Board object w/ spots
newGame.boardSetUp();
Dimension boardSize = new Dimension(600, 600);//Instantiate Visual representation of Board.
// Use a Layered Pane for this this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
//Add a chess board to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
JLabel Vpiece = new JLabel();
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );
int row = (i / 8);
if (row%2 == 0)
square.setBackground( i % 2 == 0 ? Color.darkGray : Color.white );//Adjusting for First square
else
square.setBackground( i % 2 == 0 ? Color.white : Color.darkGray );//Setting colored boxes for chess board
if(newGame.spotValues[row][i-(row*8)].piece!=null)
{
switch(newGame.spotValues[row][i-(row*8)].piece.name){
case "Bishop":
if(newGame.spotValues[row][i-(row*8)].piece.color.equals("White"))
Vpiece = new JLabel( new ImageIcon("resource/BishopW.png") );
else
Vpiece = new JLabel( new ImageIcon("resource/BishopB.png") );
break;
case "King":
if(newGame.spotValues[row][i-(row*8)].piece.color.equals("White"))
Vpiece = new JLabel( new ImageIcon("resource/KingW.png" ));
else
Vpiece = new JLabel( new ImageIcon("resource/KingB.png" ));
break;
case "Queen":
if(newGame.spotValues[row][i-(row*8)].piece.color.equals("White"))
Vpiece = new JLabel( new ImageIcon("resource/QueenW.png") );
else
Vpiece = new JLabel( new ImageIcon("resource/QueenB.png") );
break;
case "Pawn":
if(newGame.spotValues[row][i-(row*8)].piece.color.equals("White"))
Vpiece = new JLabel( new ImageIcon("resource/PawnW.png") );
else
Vpiece = new JLabel( new ImageIcon("resource/PawnB.png") );
break;
case "Rook":
if(newGame.spotValues[row][i-(row*8)].piece.color.equals("White"))
Vpiece = new JLabel( new ImageIcon("resource/RookW.png") );
else
Vpiece = new JLabel( new ImageIcon("resource/RookB.png") );
break;
case "Knight":
if(newGame.spotValues[row][i-(row*8)].piece.color.equals("White"))
Vpiece = new JLabel( new ImageIcon("resource/KnightW.png") );
else
Vpiece = new JLabel( new ImageIcon("resource/KnightB.png") );
break;
}
JPanel panel = (JPanel)chessBoard.getComponent(i);
panel.add(Vpiece);
}
}
}
public void mousePressed(MouseEvent e){
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel)
return; //makes sure no errors are given when pressed on a blank square
Point parentLocation = c.getParent().getLocation(); //parentLocation is mouse pointer
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel)c;
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
}
//Move the chess piece around
public void mouseDragged(MouseEvent me) {
if (chessPiece == null) { //checks if square is blank or not
return;
}
chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
}
//Drop the chess piece back onto the chess board
public void mouseReleased(MouseEvent e) {
if(chessPiece == null) { //checks if square is blank or not
return;
}
chessPiece.setVisible(false);
/*
* what are we doing below??
*
*
*/
System.out.print(e.getX()+" "+e.getY());
Component c = chessBoard.findComponentAt(e.getX(), e.getY()); //checks to see if there's a new piece at the new location
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
}
else {
Container parent = (Container)c;
parent.add( chessPiece );
}
chessPiece.setVisible(true);
}
/*
*
* what are we doing above??
*
*/
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new ChessGame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
最佳答案
如评论中所述,我将使用 JLabel 网格,添加和删除图标,并为我的 JLabel 提供与适当的行和列(国际象棋术语中的文件和排名)相对应的客户端属性值。我会给我的 ChessBoard 类两个字符串常量,以便在放入客户端属性以及稍后提取它们时使用:
public static final String RANK = "rank";
public static final String FILE = "file";
只需在 JLabel 上调用 putClientProperty(...)
即可添加属性:
label.putClientProperty(RANK, rank);
label.putClientProperty(FILE, file);
其中,rank 和 file 是适当的字符串。
例如,请运行这个演示程序来看看我的意思:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class SimpleChess extends JPanel {
private ChessBoard chessBoard = new ChessBoard();
private JTextField rankField = new JTextField(3);
private JTextField fileField = new JTextField(3);
public SimpleChess() {
MyMouse myMouse = new MyMouse();
chessBoard.addMouseListener(myMouse);
rankField.setHorizontalAlignment(SwingConstants.CENTER);
rankField.setFocusable(false);
fileField.setHorizontalAlignment(SwingConstants.CENTER);
fileField.setFocusable(false);
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Rank:"));
topPanel.add(rankField);
topPanel.add(Box.createHorizontalStrut(40));
topPanel.add(new JLabel("File:"));
topPanel.add(fileField);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(chessBoard, BorderLayout.CENTER);
}
class MyMouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
Component c = chessBoard.getComponentAt(e.getPoint());
if (!(c instanceof JLabel)) {
return;
}
JLabel cell = (JLabel) c;
String rank = (String) cell.getClientProperty(ChessBoard.RANK);
String file = (String) cell.getClientProperty(ChessBoard.FILE);
// icon = cell.getIcon();
rankField.setText(rank);
fileField.setText(file);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Chess");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SimpleChess());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
@SuppressWarnings("serial")
class ChessBoard extends JPanel {
public static final String RANK = "rank";
public static final String FILE = "file";
private static final int ROWS = 8;
private static final int COLS = 8;
private static final Color COLOR_LIGHT = new Color(240, 201, 175);
private static final Color COLOR_DARK = new Color(205, 133, 63);
private static final Dimension CELL_SIZE = new Dimension(60, 60);
private JLabel[][] chessTable = new JLabel[ROWS][COLS];
public ChessBoard() {
// create chess table
setLayout(new GridLayout(ROWS, COLS));
for (int i = 0; i < chessTable.length; i++) {
for (int j = 0; j < chessTable[i].length; j++) {
String rank = String.valueOf((char) ('8' - i));
String file = String.valueOf((char) ('a' + j));
JLabel label = new JLabel();
label.setPreferredSize(CELL_SIZE);
label.setOpaque(true);
Color c = i % 2 == j % 2 ? COLOR_LIGHT : COLOR_DARK;
label.setBackground(c);
label.putClientProperty(RANK, rank);
label.putClientProperty(FILE, file);
chessTable[i][j] = label;
add(label);
}
}
}
}
我正在开发一个更广泛的版本,该版本可以移动图标,但尚未完成......
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class ChessLocation extends JPanel {
public static final String RANK = "rank";
public static final String FILE = "file";
public static final String MOUSE_PRESS = "mouse press";
public static final String PIECE_IMG_PATH = "https://upload.wikimedia.org"
+ "/wikipedia/commons/thumb/b/b2/Chess_Pieces_Sprite.svg"
+ "/320px-Chess_Pieces_Sprite.svg.png"; // for smaller pieces
// + "/640px-Chess_Pieces_Sprite.svg.png"; // for larger pieces
private static final int IMG_ROWS = 2;
private static final int IMG_COLS = 6;
private static final int ROWS = 8;
private static final int COLS = 8;
private static final Color COLOR_LIGHT = new Color(240, 201, 175);
private static final Color COLOR_DARK = new Color(205, 133, 63);
private Map<ChessPiece, Icon> pieceIconMap = new HashMap<>();
private JLabel[][] chessTable = new JLabel[ROWS][COLS];
public ChessLocation(BufferedImage img) {
// get chess images and put into pieceIconMap
int w = img.getWidth() / IMG_COLS;
int h = img.getHeight() / IMG_ROWS;
for (int row = 0; row < IMG_ROWS; row++) {
int y = (row * img.getHeight()) / IMG_ROWS;
for (int col = 0; col < IMG_COLS; col++) {
int x = (col * img.getWidth()) / IMG_COLS;
BufferedImage subImg = img.getSubimage(x, y, w, h);
Icon icon = new ImageIcon(subImg);
PieceColor color = PieceColor.values()[row];
PieceType type = PieceType.values()[col];
ChessPiece chessPiece = new ChessPiece(type, color);
pieceIconMap.put(chessPiece, icon);
}
}
// create chess table
setLayout(new GridLayout(ROWS, COLS));
Dimension pieceSize = new Dimension(w, h);
for (int i = 0; i < chessTable.length; i++) {
for (int j = 0; j < chessTable[i].length; j++) {
String rank = String.valueOf((char) ('8' - i));
String file = String.valueOf((char) ('a' + j));
JLabel label = new JLabel();
label.setPreferredSize(pieceSize);
label.setOpaque(true);
Color c = i % 2 == j % 2 ? COLOR_LIGHT : COLOR_DARK;
label.setBackground(c);
label.putClientProperty(RANK, rank);
label.putClientProperty(FILE, file);
chessTable[i][j] = label;
add(label);
}
}
resetBoard();
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
public void resetBoard() {
for (JLabel[] row : chessTable) {
for (JLabel cell : row) {
cell.setIcon(null);
}
}
chessTable[0][0].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.BLACK)));
chessTable[0][7].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.BLACK)));
chessTable[7][0].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.WHITE)));
chessTable[7][7].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.WHITE)));
chessTable[0][1].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.BLACK)));
chessTable[0][6].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.BLACK)));
chessTable[7][1].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.WHITE)));
chessTable[7][6].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.WHITE)));
chessTable[0][2].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.BLACK)));
chessTable[0][5].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.BLACK)));
chessTable[7][2].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.WHITE)));
chessTable[7][5].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.WHITE)));
chessTable[0][3].setIcon(pieceIconMap.get(new ChessPiece(PieceType.QUEEN, PieceColor.BLACK)));
chessTable[0][4].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KING, PieceColor.BLACK)));
chessTable[7][3].setIcon(pieceIconMap.get(new ChessPiece(PieceType.QUEEN, PieceColor.WHITE)));
chessTable[7][4].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KING, PieceColor.WHITE)));
// put in pawns
for (int i = 0; i < PieceColor.values().length; i++) {
PieceColor color = PieceColor.values()[i];
ChessPiece piece = new ChessPiece(PieceType.PAWN, color);
for (int j = 0; j < COLS; j++) {
int row = 6 - 5 * i;
chessTable[row][j].setIcon(pieceIconMap.get(piece));
}
}
}
private class MyMouse extends MouseAdapter {
String rank = "";
String file = "";
Icon icon = null;
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
rank = "";
file = "";
icon = null;
Component c = getComponentAt(e.getPoint());
if (!(c instanceof JLabel)) {
return;
}
JLabel cell = (JLabel) c;
if (cell.getIcon() == null) {
return;
}
rank = (String) cell.getClientProperty(RANK);
file = (String) cell.getClientProperty(FILE);
icon = cell.getIcon();
// cell.setIcon(null);
}
}
private static void createAndShowGui() {
BufferedImage img = null;
try {
URL imgUrl = new URL(PIECE_IMG_PATH);
img = ImageIO.read(imgUrl);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
ChessLocation chessLocation = new ChessLocation(img);
JFrame frame = new JFrame("Chess");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(chessLocation);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
enum PieceColor {
WHITE, BLACK
}
enum PieceType {
KING(100), QUEEN(9), BISHOP(3), KNIGHT(3), ROOK(5), PAWN(1);
private int value;
private PieceType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
class ChessPiece {
private PieceType type;
private PieceColor color;
public ChessPiece(PieceType type, PieceColor color) {
this.type = type;
this.color = color;
}
@Override
public String toString() {
return "ChessPiece [type=" + type + ", color=" + color + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((color == null) ? 0 : color.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChessPiece other = (ChessPiece) obj;
if (color != other.color)
return false;
if (type != other.type)
return false;
return true;
}
}
关于java - 如何获取 8x8 GridLayout 中 JPanel 的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879323/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!