【发布时间】:2012-04-02 05:56:14
【问题描述】:
我正在开发纸牌游戏的 GUI,为了熟悉起见,我正在使用 ACM's student graphics library。我编写了一个程序,可以将我的单人纸牌游戏绘制到屏幕上,但无法使其具有交互性。
背景:
这里有很多类,我会尽力描述它们。
- 包含应用程序的顶级 JFrame。
- GCanvas(包含所有图形对象)
- SolitaireGameControl(GCompound 持有构成纸牌游戏的所有其他 GCompound)
- Array of PileViews,一堆卡片(由一组卡片组成的GCompound)
- 卡片(由矩形和标签组成的 GCompound)
- Array of PileViews,一堆卡片(由一组卡片组成的GCompound)
- SolitaireGameControl(GCompound 持有构成纸牌游戏的所有其他 GCompound)
- GCanvas(包含所有图形对象)
(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);。如果我取出这个语句,根本不会打印任何内容,这让我相信我添加的 mouseListeners 只工作了一层。 (画布上的第一个 GCompound,而不是其中的 GCompound。)
因此,我的问题如下:有没有办法为一个 GCompound inside of a GCompound inside of a GCompound 获取 MouseListener,并让 MouseEvent 的 getSource 到正确识别卡?如果没有,有没有办法重组我的程序以使其按预期工作? (我知道我真的应该为初学者使用更好的图形库。)
【问题讨论】:
-
请查看我的代码here 以了解在桌子周围拖动扑克牌的示例。
-
有趣!那么,您所做的是使用图像创建 JLabels,将它们设置到 JLayeredPane 上,然后在每个上放置一个 mouseListener?
-
另外,
Component comp = basePane.getComponentAt(mEvt.getPoint());似乎是我正在寻找可以解决我的问题的代码类型......如果同一点有多个组件,它如何确定哪一个选择?是从最顶层选卡吗?
标签: java graphics mouselistener