- 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/
我正在尝试使用 NetBeans 在 Java 中制作类似幻灯片的应用程序。 我有一个 JFrame(主窗口),里面有两个用于导航的按钮(后退和下一步),还有一个 JPanel(mainPanel),
新代码 package test; import javax.swing.*; import java.awt.*; public class TestWindow extends JFrame{ /
我是 Java swing 编码新手。我正在尝试将 JPanel 内容复制到一个新的 JPanel,它使用原始 JPanel 的内容来显示。此外,原始 JPanel 内容随着记录的变化而变化。我尝试了
我正在尝试创建一个带有另外两个 JPanel 的 JPanel,但是,当时,当我要显示主要内容时JPanel,它只显示主Jpanel上的第一个Jpanel。 通过以下示例,您将更好地理解这个问题: 我
我正在尝试学习如何使用编码风格在 Java 中完成 GUI 的工作这就是我写的: import java.awt.Container; import java.awt.Panel; import ja
我从 Oracle 教程中得到了一个 JPanel 的例子我看到它使用默认方法关闭窗口 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 我想
我在使用 Java JPanel 时遇到问题。我想将 2 个具有不同布局的 JPanel 放入一个也有布局的 JPanel 中。有可能让它发挥作用吗? BibP() setLayout(new
我试图让一个 JPanel 出现在另一个 JPanel 中。目前,JPanel 位于外部 JFrame 中,并与我的其他 JFrame 一起加载。我希望 JPanel 位于另一个 JPanel 内部,
是否可以在 Java 的一个方法中在一个面板中包含一个面板? 就像,如果我在名为 CreatePanel 的方法中创建了一个 JPanel,我可以在其下面添加另一个吗?我正在尝试在一种方法中添加两个或
我对嵌套的 BoxLayouts 有疑问。 我想构建一个由 2 个子面板组成的 DropDownPanel:顶部的标题和底部的主体。 body 最初是隐藏的。通过单击标题,您可以切换正文的可见性并显示
我需要创建一个在 JFrame 或 JPanel 上显示多个矩形的程序。这是我到目前为止提出的代码: import javax.swing.*; import java.util.Random; im
将站点中的一些图像保存到 ArrayList 后,我试图创建一个 jpanel,它将在带有滚动 Pane 的单独 jpanel 中显示所有这些图像,以便我可以向每个图像添加 Action 事件。然
我正在开发一个简单的注册窗口,它会在 Java 应用程序打开时出现。 这是一个 JFrame,里面有一个 JPanel,它有文本字段、标签,另一个面板也包含文本字段和标签。我的问题是外部面板有背景图像
我有这个界面要创建。我有 JScrollPane 的问题: 我声明了一个带有 Gridlayout(8,1,0,2) 的 JPanel,我希望在这个面板中出现 8 行。 一行是一个JPanel,我设置
我已经创建了 JFreeChart 并将其放入图表面板(按照建议)。我还将它添加到 jPanel 中。我正在使用 jFrame。但是运行程序后我的图表不可见。有谁能帮帮我吗? final JFreeC
我在下面附上了我的代码,我的程序的屏幕截图,以及我希望标签看起来像的图形。我需要我的 JPanel textPanel 出现在 LLP 选项卡上的 JButton 下方。我试图将 textPanel
我想从窗口 (JFrame) 中删除旧的 JPanel 并添加一个新的。我该怎么做呢? 我尝试了以下方法: public static void showGUI() { JFrame fram
我刚刚接触 Java,正在为我的大学类(class)开发一个项目。我正在开发一款《百万富翁》游戏,但我陷入困境。 我有一个 JFrame 类,其中有 2 个面板。第一个是由按钮组成的,第二个是我想通过
所以,我正在制作一个绘画程序,我有一个主要的Paint类,它检测鼠标输入和绘画,还有一个Tools类,它是左侧的工具栏,拥有许多工具,例如画笔大小更改和形状更改。因此,我想向 Tools 类添加一个清
我正在尝试制作一个在 JToggleButton 的帮助下激活的弹出面板。我希望在选择 ToggleButton 时将 JPanel 添加到另一个 Jpanel 上,并在取消选择 ToggleButt
我是一名优秀的程序员,十分优秀!