Прежде всего я хотел бы сказать, что я понимаю, что я очень много спрашиваю, поэтому любая помощь будет оценена, и я благодарю вас за ваше время. Я чрезвычайно благодарен.Почему моя доска не появится? Создание игры в java
Во всяком случае, я создаю игру для своей курсовой работы A2, наиболее известной как шашки. Я завершил свой код, и все работает так, как я планировал, за исключением того, что сам CheckerBoard, а также контрольно-измерительные приборы не отображаются.
Секция была моей доской должна быть просто черное пространство. Несмотря на то, что моя панель не отображается, все действия, которые я выполняю на ней, например щелчок по определенному разделу, вызывают запланированный ответ, и хотя я проверил свой код, я не могу понять, что я сделал неправильно.
В любом случае, если кто-то может заметить мою ошибку или, возможно, дать мне несколько советов, я был бы чрезвычайно благодарен. Спасибо
Как я, конечно, не могу загрузить весь мой код. Я сделаю фрагменты, где, по-моему, проблема может быть ложью или просто важными разделами. Спасибо
CheckerBoard content = new CheckerBoard(); // Sets the CheckerBoard values into the content to be used in the next line
application.setContentPane(content); // Container holds the values together, Content pane of the CheckerBoard
application.pack(); // Use preferred size of content to set size of application.
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
application.setLocation((screensize.width - application.getWidth())/2,
(screensize.height - application.getHeight())/2);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sets so that the application can be exited when the application is closed
application.setResizable(false); // This makes it so that the user can't change the application's size.
application.setVisible(true); // Sets it so that the application can actually be seen
Код выше находится в пределах «государственной статической силы основных (String [] арг)»
Тогда ниже, у меня есть:
public CheckerBoard() {
// This is going to be a constructor, this constructor will set the layout manager for the panel to be null, it will then add components to the panel
// and it will set their bounds.
setLayout(null); // So that it will match my requirement specification, I will do the layout myself
setBackground(new Color(0,120,0)); // Dark Green Background colour.
setPreferredSize(new Dimension(350,250)); // The size of the Panel
BoardComplete checkerboardData = new BoardComplete();
add(checkerboardData); // This will create the components and add them to the content pane
add(NewGameButton);
add(ResignButton);
add(MessageDisplay);
// I will now have to produce a method to set the position and size of each component by calling its setBounds() method
checkerboardData.setBounds(20,20,164,164); // Sets the board dimensions
NewGameButton.setBounds(210, 60, 120, 30);
ResignButton.setBounds(210, 120, 120, 30);
MessageDisplay.setBounds(20, 200, 350, 30);
}
И, наконец, у меня есть другой публичный класс под названием BoardComplete, который содержит весь соответствующий код, включающий ect actionlisters. используется:
BoardComplete() {
setBackground(Color.BLACK);
addMouseListener(this);
ResignButton = new JButton("Resign");
ResignButton.addActionListener(this);
NewGameButton = new JButton("New Game");
NewGameButton.addActionListener(this);
MessageDisplay = new JLabel("",JLabel.CENTER);
MessageDisplay.setFont(new Font("Serif", Font.BOLD, 14));
MessageDisplay.setForeground(Color.green);
checkerboardData = new DataForCheckers();
MakeaNewGame();
}
Я понимаю, что это много, чтобы спросить, но любая помощь будет очень признательна, и я был бы очень благодарен. Спасибо.
Редактировать из-за комментарий: Это код для моего Paint класса:
public void PaintCheckerBoard(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// This will draw a two-pixel black border around the edges of the canvas.
g.setColor(Color.black);
g.drawRect(0,0,getSize().width-1,getSize().height-1);
g.drawRect(1,1,getSize().width-3,getSize().height-3);
// Draw the squares of the checkerboard and the checkers.
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (row % 2 == col % 2)
g.setColor(Color.LIGHT_GRAY);
else
g.setColor(Color.GRAY);
g.fillRect(2 + col*20, 2 + row*20, 20, 20);
switch (checkerboardData.PieceLocation(row,col)) {
case DataForCheckers.RED:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case DataForCheckers.BLACK:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case DataForCheckers.RED_KING:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
case DataForCheckers.BLACK_KING:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
}
}
}
// If there is a game in progress, highlight the legal moves that the player can make.
// It can be seen that in this process, LegalMoves is never null while a game is in progress
if (CheckerMatchInProgress) {
/* First, draw a 2-pixel cyan border around the pieces that can be moved. */
g.setColor(Color.cyan);
for (int i = 0; i < LegalMoves.length; i++) {
g.drawRect(2 + LegalMoves[i].fromCol*20, 2 + LegalMoves[i].fromRow*20, 19, 19);
g.drawRect(3 + LegalMoves[i].fromCol*20, 3 + LegalMoves[i].fromRow*20, 17, 17);
}
// If a piece is selected to be moved, for example if ChosenRow>=0, then
// draw a 2-pixel white border around that piece, and draw a green border
// around each square that the piece can be legally moved to.
if (ChosenRow >= 0) {
g.setColor(Color.white);
g.drawRect(2 + ChosenColumn*20, 2 + ChosenRow*20, 19, 19);
g.drawRect(3 + ChosenColumn*20, 3 + ChosenRow*20, 17, 17);
g.setColor(Color.green);
for (int i = 0; i < LegalMoves.length; i++) {
if (LegalMoves[i].fromCol == ChosenColumn && LegalMoves[i].fromRow == ChosenRow) {
g.drawRect(2 + LegalMoves[i].toCol*20, 2 + LegalMoves[i].toRow*20, 19, 19);
g.drawRect(3 + LegalMoves[i].toCol*20, 3 + LegalMoves[i].toRow*20, 17, 17);
}
}
}
}
} // end PaintCheckerBoard()
так появились ваши кнопки?вы пытались добавить какой-то случайный визуальный объект в область содержимого, это похоже? Вы изменили порядок добавления элементов в область содержимого? – hexobolic
действительно вызывает revalidate() в конце справки конструктора CheckerBoard()? (после того, как вы назовете setBounds на ваших кнопках и checkerboardData) – Subler
@hexobolic Кнопки отображаются, все, кроме шахматной доски и смотрителей, шахматная доска - это просто черное пространство, что я заметил, так это то, что в BoardComplete() если вы измените setBackground (Color.BLACK) на белый, это изменит цвет раздела на белый, но контрольная панель все еще не отображается, если это какая-то проблема, поскольку, возможно, проблема может быть там? Спасибо за ваш ответ :) – Hawk97