2013-10-25 68 views
1

單擊默認「X」按鈕時,JFrame不會關閉。我認爲這個問題與主線程沒有被讀取有關,但我並不瞭解擺動的複雜性或者說老實說,一般的線程。 「窗口」是JFrame的擴展,「Boxy」驅動程序。計劃只是在初始階段。另外,我想知道如何讓主線程在每個循環中運行。在其他問題中找不到任何關於此的內容。單擊「X」按鈕時JFrame將不會關閉

public class Window extends JFrame implements KeyListener{ 
    private static final long serialVersionUID = 1L; 
JPanel panel; 
public Window(){ 
    super("FileTyper"); 
    super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    super.setSize(200,100); 
    super.setResizable(false); 
    panel = new JPanel(); 
    super.getContentPane().add(panel); 
    super.setFocusable(true); 
    addKeyListener(this); 

    super.setVisible(true); 
} 
public void update(){ 

} 
public void render(Graphics2D g){ 

} 
@Override 
public void keyPressed(KeyEvent e) { 

} 
@Override 
public void keyReleased(KeyEvent e) { 
    switch(e.getKeyCode()) { 
    case KeyEvent.VK_F9: 
     break; 
    case KeyEvent.VK_F10: 
     break; 
    } 

} 
@Override 
public void keyTyped(KeyEvent arg0) { 

} 

}

public class Boxy { 
public Window window; 

public static void main (String args[]){ 
    start(); 
} 
public Boxy(){ 
    init(); 
    boolean forever = true; 
    while(forever){ 
     update(); 
     render(); 
     delay(); 
    } 
} 
private void init(){ 
    window = new Window(); 
} 
private void update(){ 
    window.update(); 
} 
private void render(){ 
    Graphics2D g2 = (Graphics2D) window.getContentPane().getGraphics(); 
    window.render(g2); 
    g2.fillRect(0, 0, 100, 100); 
} 
private void delay(){ 
    try {Thread.sleep(20);} catch (InterruptedException ex) {System.out.println("ERROR: Delay compromised");} 
} 
public static void start(){ 
    SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      Boxy box = new Boxy(); 
     } 
    }); 
} 
} 
+0

讚譽爲是對英雄所見略同不使用抽屜的UI –

回答

4

我建議你與

while(forever){ 
    update(); 
    render(); 
    delay(); 
} 

這是防止事件隊列從處理,將關閉該窗口的事件阻塞事件調度線程。請致電Concurrency in Swing。我建議你可以先看看javax.swing.Timer之類的東西,但如果你想要更好地控制幀率,你需要使用某種Thread。請記住,Swing希望所有更新都是在事件派發線程的上下文中執行的。

風俗畫鞦韆不使用類似做...

Graphics2D g2 = (Graphics2D) window.getContentPane().getGraphics(); 

Graphics上下文短暫的,任何您的油漆給它(使用此方法)將在下一個週期的油漆被銷燬。

相反,您應該使用類似於JPanel的東西作爲繪畫的基礎,並覆蓋它的方法並在其調用時呈現其中的狀態。

當您想更新組件時,您只需致電repaint

查看Performing Custom Painting瞭解更多詳情。

我也建議你看看How to use Key Bindings爲aletrnative到KeyListener

+0

1+初學者。 –

+0

@HovercraftFullOfEels我在想同樣的事情,已經+ 1你回答 – MadProgrammer

+0

有沒有快速解決這個問題?我不打算讓這個程序太長,以至於我查看過的其他一些循環類型。這些是我的程序中的所有類 – Killam

4

你的程序的 「遊戲」 循環是不正確的:

while(forever){ 
    update(); 
    render(); 
    delay(); 
} 

而不是循環的程序,它通過捆綁起來Swing事件線程或EDT凍結它( for E排氣口D ispatch T hread)。您應該使用Swing Timer來代替此功能。