I am writing a Tetris-based game, and I am using a GridLayout to display the actual shaft which the Tetris pieces fall down. The GridLayout is filled with little JLabel objects. The shaft is itself a JPanel inside another JPanel, the panel I am using to contain and control the entire game. When th开发者_如何学Pythone game ends, I want the words "GAME OVER" to appear on top of the grid, possibly accompanied by a small image.
My shaft is an instance of ShaftPanel, which extends JPanel (so that I could override paintComponent) and is a nested private class (so it has access to private instance variables of the larger JPanel). The private instance variable it needs to access is boolean game, which is true when the game is in session and set to false when the game is over. Here is the code for my ShaftPanel class:
public class ShaftPanel extends JPanel {
public ShaftPanel(GridLayout g){
super(g);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(game)
return;
g.setColor(Color.WHITE);
g.setFont(new Font("Courier New", Font.BOLD, 15));
char[] c = {'G','A','M','E',' ','O','V','E','R'};
g.drawChars(c,0,c.length,45,45);
}
}
I have one method in the larger class calling the repaint() method of shaft at the appropriate time. Adding a print statement indicates that the paintComponent method is being called when I want it to, and the setColor, setFont, drawChars methods are all being called at the correct times. However, nothing shows up. I highly suspect that the text is being drawn underneath the grid of JLabels, so that it can't be seen, but I don't know how to fix this problem. The JLabels inside the grid have to stay opaque, because the program relies on them being different colors. Is there a way to tell paintComponent to draw the text on top of anything else in the panel?
See the section from the Swing tutorial on Using a Glass Pane for an example and explanation on how a glass pane works.
Another option is to use a JWindow to display a label with your message and icon.
I would probably not have made tetris this way, but one way to test this would be to remove the "if(game)" and see if game over is being written even when no JLabels are there (unless they are always there and sometimes are blank).
At any rate, I think what might be useful though I don't think I have ever used it is a GlassPanel.... This is a panel that can be overlayed on your current JFrame etx...
Look Here for more code and info: http://www.java2s.com/Code/Java/Swing-JFC/Paintonglasspane.htm
精彩评论