我正在用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...
}
由于某些错误,当典当到达最终图块时,将不显示任何内容,并且应用程序将按原样继续运行。
答案 0 :(得分:0)
经过数小时的调试后,我终于以某种方式使它正常工作。我所做的是我添加了SwingUtilities.invokeLater()方法,并像这样传递了其中的代码。
case PROMOTION:
moveMade.initialTile.removePiece();
SwingUtilities.invokeLater(() -> {
JPanel promotionOptions = new PromotionOptions(colorToMove.opposite);
promotionOptions.setLocation(clickedTile.getLocation());
layeredPaneContainer.add(promotionOptions, 2);
layeredPaneContainer.revalidate();
});
break;