gpt4 book ai didi

java - 在 JPanel Netbeans 上获取单击目标

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:43 24 4
gpt4 key购买 nike

我是 Java 编程新手,并且 >我正在尝试制作 2D 游戏。我在网站上搜索我的问题的答案,但没有找到,所以我希望我做的是正确的事情。因此,我得到了一个名为 Board 的类,它扩展了 JPanel 并实现了 ActionListener。在这个板上我画了一些“区域”,它是一个带有关联图像的类。我的问题是,当我单击面板时,我想获取我单击的“区域”,但实际上我通过事件 mouseClicked 获取了面板。我希望我能理解,这是 Board 类:

public class Board extends JPanel implements ActionListener {
private List<Zone> zones = new ArrayList<Zone>();

public Board() {
addMouseListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
Dalle[] dalle1C = new Dalle[]{new Dalle()};
zones.add(new Zone(false, false, dalle1C, null, "zone1D1C.jpg", 0, 0));
zones.add(new Zone(false, false, dalle1C, null, "zone2D1C.jpg", 150, 0));
timer = new Timer(5, this);
timer.start();
}

public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
for (Zone zone : zones) {
g2d.drawImage(zone.getImage(), zone.getX(), zone.getY(), this);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}

public void actionPerformed(ActionEvent e) {
repaint();
}


private class TAdapter extends MouseAdapter {

public void mouseClicked(MouseEvent e) {
//Here, instead of using x,y positions I want to get something like "e.getClickedObject()"
Integer x = e.getX();
Integer y = e.getY();
Zone zone_selected = null;
for (Zone zone : zones) {
if (x > zone.getX() && x < zone.getX_end() && y < zone.getY_end() && y > zone.getY(){
zone_selected = zone;
}
}
zones.remove(zone_selected);
// And Here I want to use repaint method but this is not possible if you have a solution...
}
}

}

和区域类:

public class Zone {
private String name;
private boolean piece;
private boolean egout;
private List<Dalle> dalles = new ArrayList<Dalle>();
private List<Connexion> connexions = new ArrayList<Connexion>();
private List<Personnage> personnages = new ArrayList<Personnage>();
private Image image;
private Integer x;
private Integer y;
public Integer x_end;
public Integer y_end;

public Zone(boolean piece, boolean egout, Dalle[] dalles, List<Connexion> connexions, String image_name, Integer x, Integer y) {
this.piece = piece;
this.egout = egout;
this.dalles.addAll(Arrays.asList(dalles));
for(Dalle dalle : dalles) {
dalle.addZone(this);
}
this.name = image_name;
this.connexions = connexions;
ImageIcon ii = new ImageIcon(this.getClass().getResource(image_name));
image = ii.getImage();
this.x = x;
this.y = y;
this.x_end = x + image.getWidth(null);
this.y_end = y + image.getHeight(null);
}

最佳答案

Board 这样的 JComponent 会看到相对于其左上角的鼠标事件,默认情况下是点 (0, 0)。要获取内部坐标,您可以

  • 使用组件网格,如图 here .

  • 通过坐标的线性缩放来插值点,如图 here .

关于java - 在 JPanel Netbeans 上获取单击目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com