JMenuBar
을 맨 위에 구현하는 JFrame
을 구축 중입니다. 프레임의 나머지 부분은 JComponent
이며, 이중 공백 래스터 이미지를 통해 화면 주위를 움직이는 움직이는 공이 들어 있습니다. 메뉴 항목을 클릭 할 때마다 깜박이지만 완전히 표시되지는 않습니다. 내 JComponent
(어느 paintComponent()
그릴 사용) 어떤 이유로 내 메뉴를 은폐합니까? 필자가 별도의 JComponent
을 작성한 이유는 요소 간의 충돌을 피하기 위해서였습니다. 내 JFrame
및 JComponent
의 코드는 다음과 같습니다.JMenuBar가 활성화되지 않는 이유는 무엇입니까? (클릭하면 깜박이지만 완전히 표시되지 않음)
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();
}
}