我正在用 Swing 编写一个 2D 游戏。对于菜单,我使用 JButtons,现在我想使用 JPasswordField。问题是:如果我尝试在其中写一些东西,程序就会崩溃。我将错误定位到这一行代码:
frame.getLayeredPane().paintComponents(graphics);
密码字段未正确绘制,程序崩溃。但是如果我不使用这条线,就不会出现任何组件。我认为这是因为我使用了双缓冲,但我需要它用于游戏本身。
JFrame 在这里创建:
public void createFrame() {
RepaintManager.setCurrentManager(new RepaintManager() {
@Override
public void addDirtyRegion(final JComponent c, final int x, final int y, final int w, final int h) {}
@Override
public void addInvalidComponent(final JComponent invalidComponent) {}
@Override
public void markCompletelyDirty(final JComponent aComponent) {}
@Override
public void paintDirtyRegions() {}
});
frame = new JFrame("Bubble Trouble");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maximizeFrame(getFirstCompatibleMode(displayModes));
//setFullScreen(getFirstCompatibleMode(displayModes));
frame.setResizable(false);
frame.setUndecorated(true);
frame.setIgnoreRepaint(true);
frame.setVisible(true);
((JComponent) frame.getContentPane()).setOpaque(false);
JPanel panel = new JPanel();
main.getComponentHandler().initComponents(panel);
main.getKeyHandler().registerKeys(main.getComponentHandler().getPanel());
panel.setOpaque(false);
panel.addMouseListener(main.getMouseListener());
frame.getContentPane().add(panel);
frame.createBufferStrategy(2);
}
调用此方法来重新绘制并刷新游戏:
public void draw() {
Graphics graphics = null;
JFrame frame = screenHandler.getFrame();
BufferStrategy bufferStrategy = frame.getBufferStrategy();
try {
graphics = (Graphics) bufferStrategy.getDrawGraphics();
switch(main.getStatus()) {
case MENU_MAIN: drawMainMenu(graphics); break;
case MENU_GAME: drawGameMenu(graphics); break;
case GAME: drawGame(graphics); break;
case LEVELCHANGE: drawLevelChange(graphics); break;
case SCORE: drawScore(graphics); break;
}
drawHertz(graphics);
graphics.translate(frame.getInsets().left, frame.getInsets().top);
frame.getLayeredPane().paintComponents(graphics);
if (!bufferStrategy.contentsLost())
bufferStrategy.show();
} catch (IllegalStateException e) {}
finally {
if (graphics != null) graphics.dispose();
}
Toolkit.getDefaultToolkit().sync();
Thread.yield();
}