簡體   English   中英

如何將MouseListener添加到另一個圖形對象內的圖形對象?

[英]How do I add a MouseListener to a graphics object inside another graphics object?

我正在為紙牌游戲設計GUI,並且為了熟悉起見,正在使用ACM的學生圖形庫 我編寫了一個程序,將我的單人紙牌游戲繪制到屏幕上,但無法使其具有交互性。

背景:

這里有很多類,我將盡力描述每個類。

  • 包含應用程序的頂級JFrame。
    • GCanvas(包含所有圖形對象)
      • SolitaireGameControl(GCompound容納組成紙牌游戲的所有其他GCompounds)
        • 一組PictureViews,一堆紙牌(由一組紙牌組成的GCompound)
          • 卡(由矩形和標簽組成的GCompound)

GCompound:被視為一個對象的圖形對象的集合。(如果car是GCompound,它將具有GOval[] wheels, GRect body ,因此當我將其添加到畫布中時,它將顯示為一個對象))

從頂級類中看到的卡片看起來像這樣: jFrame.gCanvas.solitaireGameControl.pileViews[pile number].cardView

我一直想做的是向每張卡中添加一個MouseListener,以便在單擊卡並觸發MouseEvent時,MouseEvent e.getSource() =被單擊的卡。

現在是這樣的:

public SolitaireGameControl(SolitaireGame game) {
    this.game = game; // Model of the game.
    this.pileViews = PileView.getPileViews(game.drawPiles); // ArrayList of PileViews (the pile of cards)

    for(PileView pv : pileViews) {
        for(CardView cv : pv.cardViews) {
            cv.addMouseListener(this); // add a mouseListener to the card
        }
    }

    this.addMouseListener(this); // if I don't include this, nothing happens when I click anything. If I do include this, this whole object is the source.
}

@Override
public void mouseClicked(MouseEvent e) {
    System.out.println(e.getSource()); // should return the card I clicked.
}

問題圖片

當我運行該程序時,每個事件的源頭都是SolitaireGameControl, this.addMouseListener(this);是我留在this.addMouseListener(this); 如果我刪除該語句,則什么都不會打印,這使我相信我添加的mouseListeners只能深入一層。 (畫布上的第一個GCompound,而不是其中的GCompounds。)

因此,我的問題如下:是否有辦法在GCompound 內的 GCompound 獲取GCompound的MouseListener,並使MouseEvent的getSource正確識別卡? 如果沒有,是否可以重組程序以使其按預期工作? (我知道我確實應該為初學者使用更好的圖形庫。)

那是有道理的。 根據我的經驗,如果我將某些組件放在頂層容器中,則該容器就是接收輸入事件的容器。

您是否嘗試過執行以下操作的方法:

/* This is the mouse listener for the top-level container. */
@Override
public void mouseClicked(MouseEvent e) {
    for(PileView pv : pileViews) {
        for(CardView cv : pv.cardViews) {
            if(cv.getBounds().contains(e.getPoint())) {
                cv.dispatchEvent(e);
            }
        }
    }
}

...然后正常處理“ CardView”級別的鼠標單擊。

當頂級容器收到鼠標事件時,它將根據事件的位置(如果卡的區域包含該點)檢查鼠標是否與卡進行了交互。 如果是這樣,它將鼠標事件傳遞給卡的鼠標偵聽器。

我假設“ pv.cardViews”開頭附近的元素是最靠前的卡片。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM