我遇到的問題非常簡單 - 我使用Java AWT(和Swing)來製作遊戲,但最初的Graphics.drawString(String str, int x, int y)
調用時間太長。我沒有設置自定義字體或任何東西。我沒有設置任何渲染提示。我在MacBook Air中使用Mac Sierra 10.12.4 - 我沒有在Windows中測試我的程序。如果這一點很重要。Java AWT初始drawString()調用需要長
如果你不想花時間讀最小的例子,我有一個名爲GamePanel的類,它擴展了JPanel(並實現了runnable),我將它添加到主方法中的JFrame中。我在構造函數中初始化遊戲線程,並在run()
方法中啓動遊戲循環。遊戲循環然後使用Swing Timers重複自己。在遊戲循環中,我通過redraw()
調用paintComponent(Graphics g)
- 文本以paintComponent
方法繪製。這並不是真正必要的信息,因爲這個問題在沒有遊戲循環的情況下是可以重現的,只需要使用遊戲線程和paintComponent
方法,但我只是在這裏提出這個問題。
任何幫助表示讚賞。
遊戲類(JFrame的)
public class Game {
public static JFrame frame;
public static JPanel gamePanel;
public static void main(String[] args) {
frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(new BorderLayout());
gamePanel = new GamePanel();
frame.add(gamePanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
的GamePanel類(面板)
public class GamePanel() extends JPanel implements Runnable {
public static Thread thread;
public GamePanel() {
super();
setPreferredSize(new Dimension(640, 480));
setFocusable(true);
requestFocus();
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
while (! Game.frame.isVisible()) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
EventQueue.invokeLater(new Runnable() {
public void run() {gameLoop();}
});
}
public void GameLoop() {
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
gameLoop();
}
public void paintComponent(Graphics g) {
super.paintComponent();
g.drawText("Hello World", 10, 10);
}
}
我知道在小例子的速度的遊戲循環會不斷變化(和多數民衆的完全相反一個好的遊戲循環應該做什麼)。但是最小的例子有什麼關係呢?
好吧,我明白了...謝謝你的回答。不過,我現在還有一個問題。我將如何繼續討論gameloop?我會在EventDispatching線程中運行整個遊戲循環嗎? – MaiorExMinor
我對Java的遊戲開發瞭解不多,但是我創建了非常簡單的遊戲,我剛剛在EDT上使用了一個帶有scheduleAtFixedRate的TimerTask來更新我的對象。如果我要創建一個更復雜,更大的遊戲,我會明確地去圖書館來幫助渲染。我已經玩了一些libgdx,我喜歡它https://libgdx.badlogicgames.com/但在創建遊戲的過程中,我不是正確的人回答我認爲的問題。祝你好運,並與發展樂趣! – LanfeaR
我不接受答案,因爲新的編輯使這個答案無關緊要。不過,謝謝。 – MaiorExMinor