我正构建一个JFrame
,在顶部实现JMenuBar
。帧的其余部分是JComponent
,其中包含一个围绕屏幕移动的动画球(通过双缓冲光栅图像)。每当我点击菜单项时,它们都会闪烁,但不会完全显示。由于某种原因,我的JComponent
(使用paintComponent()
绘制)是否覆盖了我的菜单?我创建一个单独的JComponent
的全部原因是为了避免元素之间的冲突。以下是我的JFrame
和JComponent
的代码。
public class Driver
{
public static void main(String[] args)
{
// Creates Game window.
MyFrame myFrame = new MyFrame();
DrawingSurface drawingSurface = new DrawingSurface();
myFrame.add(drawingSurface);
drawingSurface.setup();
myFrame.makeMenu();
drawingSurface.paintGomponent();
}
}
class MyFrame extends JFrame
{
/**
* Default serial version of long defined to suppress serial warning.
*/
private static final long serialVersionUID = 1L;
public MyFrame()
{
setTitle("Breakout");
setSize(800,600);
setResizable(false);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Sets location to center of screen (stackoverflow.com)
setVisible(true);
}
public void makeMenu()
{
JMenuBar menuBar = new JMenuBar();
// Adds menu "Game" with sub-menu "New", "Pause" and "Exit".
JMenu game = new JMenu("Game");
JMenuItem newGame = new JMenuItem("New");
newGame.setToolTipText("Starts a new game");
JMenuItem pauseGame = new JMenuItem("Pause");
pauseGame.setToolTipText("Pauses the game");
JMenuItem exitGame = new JMenuItem("Exit");
exitGame.setToolTipText("Exits the game");
// Adds menu "High Score".
JMenu highScores = new JMenu("High Scores");
highScores.setToolTipText("Displays high scores");
// Adds menus to menu bar and sets menu bar to frame.
game.add(newGame);
game.add(pauseGame);
game.add(exitGame);
menuBar.add(game);
menuBar.add(highScores);
setJMenuBar(menuBar);
}
}
class DrawingSurface extends JComponent
{
private int XResolution = 800;
private int YResolution = 600;
private Image raster;
private Graphics rasterGraphics;
public void paintGomponent()
{
super.paintComponent(rasterGraphics);
// Player ball used in game.
Ball ball = new Ball(400, 300, 2.0f, 1.0f);
while(true)
{
// Time for use with sleep, to make game run more smoothly.
long time = System.currentTimeMillis();
drawBackground();
ball.moveBall(ball);
ball.drawBall(rasterGraphics);
// Draws buffered raster graphics to frame.
getGraphics().drawImage(raster, 0, 0, XResolution, YResolution, null);
long changeInTime = System.currentTimeMillis() - time;
try{Thread.sleep(10-changeInTime);}catch(Exception e){}
}
}
private void drawBackground()
{
rasterGraphics.setColor(Color.black);
rasterGraphics.fillRect(0, 0, XResolution, YResolution);
}
public void setup()
{
raster = createImage(XResolution, YResolution);
rasterGraphics = raster.getGraphics();
}
}
答案 0 :(得分:0)
我的JComponent(使用paintComponent()绘制)是否出于某种原因覆盖我的菜单?
您没有使用paintComponent()方法,这可能是问题所在。您使用"G"
而不是"C"
创建了自己的方法,然后尝试使用Graphics,而不是通常传递给paintComponent()方法的Graphics。
不要喜欢你的代码。只需将绘制代码放在paintComponent()方法中并使用其Graphics对象即可。
在绘画代码中没有while循环,只需使用Swing Timer来安排动画。
阅读Custom Painting上Swing教程中的部分,了解更多信息和示例。