我在java中制作检查器,当我点击GUI时,“New Game”按钮消失了。当我将鼠标悬停在鼠标上时会重新出现,但如果单击GUI,它将再次消失。你知道我做错了什么/我做错了吗?
public void setFrame()
{
boardSize = 10;
squareSize = 50;
int imageSize = boardSize * squareSize;
image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
imageIcon = new ImageIcon(image);
jLabel = new JLabel(imageIcon);
button = new JButton("New Game");
button.setFocusable(false);
button.setBounds(375, 5, 100, 20);
pnl = new JPanel();
pnl.setBounds(400, 10, 200, 100);
pnl.setLayout(null);
pnl.add(button);
jFrame = new JFrame("Checker Board");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.add(jLabel, BorderLayout.CENTER);
jFrame.add(pnl);
jFrame.setSize(506, 558);
jFrame.setResizable(false);
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
jFrame.validate();
}
/**
* Paint the checker board onto the Image.
*/
public void paint()
{
Graphics graphics = jFrame.getGraphics();
pnl.paint(graphics);
button.paint(graphics);
graphics.setColor(Color.black);
Font font = new Font("Score", Font.BOLD, 20);
graphics.setFont(font);
graphics.drawString("Score: ", 150, 47);
graphics.drawString("Turn: ", 20, 47);
graphics.setFont(font.deriveFont(0, 16.0F));
graphics.drawString("Red: " + Game.score.getScoreRed() + " Black: " + Game.score.getScoreBlack(), 230, 47);
graphics.drawString((Game.redTurn ? "Red" : "Black"), 80, 47);
// paint a red board
graphics.setColor(Color.red);
graphics.fillRect(xShift, zShift, boardSize * squareSize, boardSize * squareSize);
// paint the black squares
graphics.setColor(Color.black);
for (int row = 0; row < boardSize; row++)
{
for (int col = row % 2; col < boardSize; col += 2)
{
graphics.fillRect( row * squareSize + xShift, col * squareSize + zShift, squareSize, squareSize );
}
}
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
if(Game.board.pieces[i][j] != null)
{
Color pieceColor = Game.board.pieces[i][j].getColor().equals(EnumTeam.BLACK) ? Color.gray : Color.pink;
graphics.setColor(pieceColor);
graphics.fillOval((i * 50) + 10 + xShift, (j * 50) + 10 + zShift, 30, 30);
if(Game.board.pieces[i][j].isKing())
{
pieceColor = Game.board.pieces[i][j].getColor().equals(EnumTeam.BLACK) ? Color.darkGray : Color.magenta;
graphics.setColor(pieceColor);
graphics.fillOval((i * 50) + 20 + xShift, (j * 50) + 20 + zShift, 10, 10);
}
}
}
}
graphics.setColor(Color.cyan);
drawRect(graphics, Game.board.getSelectedX(), Game.board.getSelectedZ(), 5);
}
答案 0 :(得分:3)
不要,永远使用Graphics graphics = jFrame.getGraphics();
(或getGraphics
一般)!这不是自定义绘画在Swing中完成的方式。事实上,你随后清除了图形上下文是你的核心问题。
所有绘画都应该在绘画API的上下文中完成,最好是从paintComponent
扩展的任何组件覆盖JComponent
(我个人更喜欢JPanel
)
创建一个自定义组件并使用它来执行自定义绘制。与框架上的其他组件一起布局。
设置Performing Custom Painting和Painting in AWT and Swing以获取有关绘画如何在Swing中工作的更多详细信息。
MouseListener
并不适合用作按钮,更好的选择是使用考虑鼠标点击和键盘事件的ActionListener
...
有关详细信息,请参阅How to write an Action Listener和How to use buttons