2015-04-12 54 views
0

在Netbeans IDE中,我編寫了一個程序在JFrame中創建一個JButton。 JButton是可見的,並且是可點擊的,但是當JButton被點擊時,有時程序不會檢測到它。發生這種情況是總是當我從.jar文件運行Netbeans自動編譯。我的代碼,等待被點擊將JButton如下:JButton在IDE中將會點擊,但不會在.jar文件中

while(!(btn.getModel().isPressed())){ //btn is the JButton here 
} 

這個工程在NetBeans,當我運行它在IDE中,但是當程序與運行時點擊的JButton它從未檢測.jar文件。我嘗試過的一件事是在循環中添加一個延遲。起初我以爲,環管循環太快太檢測單一的點擊,所以我加了1毫秒之間的延遲:

while(!(btn.getModel().isPressed())){ 
    try{ 
     Thread.sleep(1); 
    }catch(InterruptedException e){ 
     '//Exception handling 
    } 
} 

這也適用於IDE,但它仍然不工作.jar文件。 btn.getModel().isPressed()有問題嗎?如果有問題,btn.getModel().isPressed()有什麼好的選擇?

回答

0

您可能想嘗試使用ActionListener。

要一個ActionListener添加到您的按鈕,使用此: btn.addActionListener(new ActionListener(){ }); 現在你已經這樣做了,在ActionListener的裏面,把這個方法: public void actionPerformed(ActionEvent arg0){ } 現在你已經這樣做了,請將Thread.sleep(1)actionPerformed方法。

+0

我會嘗試,但你能解釋爲什麼它只是在我的IDE中點擊嗎?這對我仍然很困惑。 – pasghetti

相關問題