【问题标题】:Removing panels from an array [closed]从阵列中删除面板[关闭]
【发布时间】:2016-07-30 02:47:22
【问题描述】:

我创建了一个 10 x 10 的 Jpanels 数组,我必须从其中删除一个正方形。被点击的方块必须被移除,它下面和右边的所有方块也是如此。 目前,当我单击一个正方形时,它只会删除一个正方形。 http://imgur.com/a/6wZYA - 这是网格的样子,然后是预期的结果。 下面附上我目前正在使用的代码。欢迎任何帮助。如果我需要附加更多代码,请告诉我,谢谢。

    for (int x = 0; x < 10; x++) {
        playingGrid[x] = new JPanel[10];
        for (int y = 0; y < 10; y++) {
            playingGrid[x][y] = new JPanel();
            playingGrid[x][y]= new ImagePanel(Toolkit.getDefaultToolkit()
                                  .getImage("rock.jpg"));   
            pcenter.add(playingGrid[x][y]);
            playingGrid[x][y].addMouseListener(new Rockbreaker());
        }

    }
    f.getContentPane().add(pcenter, BorderLayout.CENTER);

}
public class Rockbreaker implements MouseListener{

    public void mouseClicked(MouseEvent e) {
         //sets all columns greater than one clicked to invisible 
        for (int x = 0; x < 10; x++) {
            for (int y = 0; y < 10; y++) {
                if(playingGrid[x][y]== e.getSource()){                  
                        for (int c=0;c<100;c++){
                            if(c>x){
                                playingGrid[x][y].setVisible(false);
                            }
                        }

【问题讨论】:

  • 我已删除您的 JavaScript 标签,因为您的问题与该语言无关,并添加了 Swing 标签,因为您的问题与该库有关。但至于您的实际问题,也许是我,但我不知道您要做什么或您在尝试中遇到什么问题。如果您没有很快得到一个体面的答案,请认真考虑改进这个问题,包括发布更多相关且解释清楚的详细信息以及符合minimal reproducible example 的代码帖子。
  • 另外,为什么要为网格分配一个新的 JPanel playingGrid[x][y],然后立即丢弃这个 JPanel 对象并分配一个完全不同的对象,一个 ImagePanel 到相同的网格位置?这没有任何意义。
  • 另外,如果这是我的项目,我可能不会更改网格中 JPanel 的可见性,因为这可能会弄乱网格中所有可见组件的布局,而是会可能会使用 JLabel 网格,并且会简单地交换标签显示的图标。
  • 嘿,感谢气垫船提供的所有这些提示,如果我的问题格式等在试图习惯这个网站时很糟糕,我现在已经解决了这个问题。感谢您抽出宝贵时间:)
  • "..我现在已经解决了这个问题。"'no MCVE'的问题仍然很明显..

标签: java arrays swing loops for-loop


【解决方案1】:

你的逻辑有缺陷。我不确定您在 if (c>x) 块中要做什么,但您可以轻松地将其重写为

public void mouseClicked(MouseEvent e) {
    int selectedX = -1;
    int selectedY = -1;
    for (int x = 0; x < 10; x++) {
        for (int y = 0; y < 10; y++) {
            if(playingGrid[x][y]== e.getSource()){
                playingGrid[x][y].setVisible(false);
                selectedX = x;
                selectedY = y;
            } else if (selectedX > 0 && selectedY > 0 && selectedX <= x && selectedY <= y) {
                playingGrid[x][y].setVisible(false);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多