我试图制作国际象棋游戏,但我无法弄清楚如何顺利地重绘我的细胞。我希望每次一件作品都能重新绘制它们。我试图继续添加Jframes,但它会让它回到旧框架上。有没有一种简单的方法来更新GUI的某些部分?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI {
public static JFrame frame; //global variable for drawn frame
public static ChessBoardPane tiles;
public GUI(final Piece[][] board) { //GUI for Board and Pieces
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
frame = new JFrame("Chess"); //initialize frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //closes on exit
drawFrame(board); //draw frame
}
});
}
public void drawFrame(final Piece[][] board){ //updates gui with a new frame
try{
tiles=new ChessBoardPane(board);
frame.add(tiles); //add chess board to frame
frame.pack(); //resizes frame to fit chess grid
frame.setLocationRelativeTo(null); //window in middle of screen
frame.setVisible(true); //visible
} catch(Exception ex){
}
}
public class ChessBoardPane extends JPanel{ //creates a grid of jButtons
public ChessBoardPane(Piece board[][]) {
int index = 0;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int row = 0; row < Board.width; row++) {
for (int col = 0; col < Board.height; col++) {
Color color = index % 2 == 0 ? Color.LIGHT_GRAY : Color.DARK_GRAY; //cells are dark and light gray
gbc.gridx = col;
gbc.gridy = row;
String symbol;
if(board[col][Board.height-row-1]!=null){
symbol=board[col][Board.height-row-1].symbol; //chooses the correct picture for a piece
}
else
symbol=null;
Cell tile = new Cell(color,symbol);
tile.addActionListener(new ButtonActionListener(col, Board.height-row-1));
add(tile, gbc); //add cell to gui
index++;
}
index++;
}
}
private class ButtonActionListener implements ActionListener{ //used to get x and y coordinates for button presses and call methods
private int x;
private int y;
public ButtonActionListener(int x, int y){
this.x=x;
this.y=y;
}
public void actionPerformed(ActionEvent e){ //runs commands when a tile is pressed
Game.attemptMove(x,y);
}
}
}
public class Cell extends JButton { //sets up cell behavior
int x;
int y;
public Cell(Color background, String symbol) {
setContentAreaFilled(false);
if(symbol!=null){
ImageIcon img = new ImageIcon(symbol); //puts picture in cell
setIcon(img);
}
setBorderPainted(false);
setBackground(background); //sets cell color
setOpaque(true);
}
@Override
public Dimension getPreferredSize() { //sets size of cell
return new Dimension(75, 75);
}
}
}