2017-05-09 42 views
0

我想爲使用JSpinner和JOptionPane的小項目創建一個簡單的菜單。我創建了所需的輸出,但是當我與窗口交互,甚至超過在框中的按鈕徘徊,一遍又一遍產生視覺假象再次(見下面的圖片):Java JOptionPane來自窗口交互的視覺神器

JOptionPane before mouse hover

JOptionPane after mouse hover

我做了一些研究,並認爲它可能是由於JOptionPane不是線程安全的,但沒有得到任何工作。

總的來說,我的具體問題是如何防止Java通過JOptionPane窗口重新繪製這些視覺工件?

僅供參考,請參閱我使用的顯示此菜單的方法:

import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.SpinnerNumberModel; 
import javax.swing.JSpinner; 

public class Battleship 
{ 
    public static void main(String[] args) 
    { 
     SpinnerNumberModel battleshipRange = new SpinnerNumberModel(1, 1, 5, 1); 
     JSpinner rangeSpinner = new JSpinner(battleshipRange); 
     JOptionPane.showMessageDialog(null, rangeSpinner, "Battleship Number", JOptionPane.QUESTION_MESSAGE); 
    } 
} 

我運行在BlueJ的這段代碼和我使用的是Windows 10專業版。

如果這是一個初學者問題,請提前致謝並表示歉意。我對編程還很陌生。

編輯:更新代碼以提供完整的問題源,但它消失。我會密切關注,看看錯誤發生的源頭在哪裏。

+1

發佈4行代碼並不能幫助我們。發佈一個證明問題的適當的[mcve]。這是根據你對問題的描述,你所需要的只是一個帶微調控制器的選項面板,當然還有一個顯示選項面板的main()方法。在創建例子時你會發現問題的機會。 – camickr

+1

我重構了我的代碼以提供一個合適的示例,但現在錯誤消失了。即使重新啓動我的程序也會使問題消失。當我開發我的程序以查看問題是否再次出現時,我會繼續關注它。感謝您的反饋意見。它幫助我縮小了這個問題的範圍,並將幫助我在未來提出更好的問題。 – Phillip

回答

0

完成我的項目後,我終於找到了爲什麼視覺工件會彈出所有按鈕/單選按鈕/等。在我的比賽中。

在GridWorld源代碼的「GridPanel.java」腳本下,原始程序員創建了一個名爲「setToolTipsEnabled(boolean flag)」的方法。它的功能是當遊戲停止運行時,在遊標懸停在網格上方時彈出消息框。

當擴展GridWorld以創建我的項目時,該方法超出網格結構並嘗試在光標懸停的任何內容之下創建工具提示。因此,在按鈕/單選按鈕/等上創建視覺工件。

爲了解決這個問題,我確定這個方法總是設置爲false,因爲我不需要我的遊戲的工具提示。該方法在「GridPanel.java」和「GUIController.java」腳本中實現(在GridWorld代碼中)。我改變了下面的方法來解決這個問題:

/** 
* Stops any existing timer currently carrying out steps. 
* Phillip Sturtevant Note: keep tool tips hidden to prevent visual artifacts 
*/ 
public void stop() 
{ 
    display.setToolTipsEnabled(false); // hide tool tips while stopped 
    timer.stop(); 
    running = false; 
} 

或者

GridPanel.java

/** 
* Construct a new GridPanel object with no grid. The view will be 
* empty. 
*/ 
public GridPanel(DisplayMap map, ResourceBundle res) 
{ 
    displayMap = map; 
    resources = res; 
    // Phillip Sturtevant: Commented out to prevent visual artifacts 
    //setToolTipsEnabled(true); 
} 

GUIController.java,方法調用可以被完全省略,但是我的情況下,註釋出來我將來需要他們。

僅供參考,下面的方法將在GridWorld工具提示知名度(位於「GridPanel.java」):

/** 
* Enables/disables showing of tooltip giving information about the 
* occupant beneath the mouse. 
* @param flag true/false to enable/disable tool tips 
*/ 
public void setToolTipsEnabled(boolean flag) 
{ 
    if ("hide".equals(System.getProperty("gridworld.gui.tooltips"))) 
     flag = false; 
    if (flag) 
     ToolTipManager.sharedInstance().registerComponent(this); 
    else 
     ToolTipManager.sharedInstance().unregisterComponent(this); 
    toolTipsEnabled = flag; 
}