【发布时间】:2019-04-14 18:20:56
【问题描述】:
我正在用 Java 构建一个国际象棋程序。我无法在 jPanel(即董事会)的顶部显示包含促销选项的 jPanel。
棋盘位于 JLayeredPane 内,当棋子到达最后一个方格时,我在事件处理程序中实例化 PromotionOptions 面板并重新验证。但是 jPanel 没有显示出来。
我已经尝试为 jPanel 对象设置适当的大小和位置,放置 revalidate(),也使用了 repaint() 方法。我还明确为 JLayeredPane 分配了 null 布局。
stackoverflow 中与此相关的所有问题都已通过正确设置布局来解决,这似乎不是这里的问题...
// JLayeredPane created here...
class Game extends JFrame {
Game() {
super.setLayout(new TableLayout(new double[][]{{0.5, 475, 0.5}, {0.5, 475, 0.5}}));
JLayeredPane layeredContainer = new JLayeredPane();
layeredContainer.setLayout(null);
Board board = new Board(layeredContainer);
board.arrange();
layeredContainer.add(board, 1);
board.setSize(475, 475);
super.add(layeredContainer, "1, 1");
super.setSize(600, 600);
super.setResizable(false);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.validate();
}
}
// 此处创建的 PromotionOptions...
public class Board extends JPanel {
//skipping some irrelevant code...
private class PromotionOptions extends JPanel {
private PromotionOptions(PieceColor color) {
super.setSize(50,200);
super.setBackground(Color.WHITE);
super.setLayout(new GridLayout(4, 1));
ImageIcon queenIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "Q.png"));
ImageIcon rookIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "R.png"));
ImageIcon bishopIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "B.png"));
ImageIcon knightIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "N.png"));
JLabel queenLabel = new JLabel(queenIcon);
JLabel rookLabel = new JLabel(rookIcon);
JLabel bishopLabel = new JLabel(bishopIcon);
JLabel knightLabel = new JLabel(knightIcon);
super.add(queenLabel);
super.add(rookLabel);
super.add(bishopLabel);
super.add(knightLabel);
}
}
// skipping some more irrelevant code...
private void executeMove(Tile clickedTile) {
// skip to where I create the PromotionOption object and add to layeredPane...
case PROMOTION:
moveMade.initialTile.removePiece();
JPanel promotionOptions = new PromotionOptions(colorToMove);
promotionOptions.setLocation(200,200);
layeredPaneContainer.add(promotionOptions, 2);
layeredPaneContainer.revalidate();
break;
// Some more code here
}
// End of Board class...
}
由于一些错误,当 pawn 到达最后一个图块时,什么都不会显示,应用程序会继续运行。
【问题讨论】:
标签: java swing user-interface jlayeredpane