【问题标题】:Variable to store objects?存储对象的变量?
【发布时间】:2013-06-12 23:33:16
【问题描述】:

我正在尝试使用 java swing 创建一个人类国际象棋程序。我有 64 个jPanels 背靠背(在灰色和白色背景颜色之间交替),每个内部都有一个 jLabel,用于显示碎片的图标。

现在我正在尝试制作它,以便您可以通过连续单击面板将一块面板从一个面板移动到另一个面板。我还使用了一个名为“board”的图标数组来存储所有棋子的位置。

到目前为止,程序成功地将第一个点击的jPanel 的图标复制到了第二个(并对板阵列进行了相应的更改)。但是,我无法从第一次点击的jPanel 中删除图标,以便该作品真正“移动”,而不仅仅是复制。

我知道我需要将最初选择的面板存储在某种变量中,然后在单击第二个面板时使用该变量将原始jPanel 的图标设置为null。但是,对于选定的面板(1-64)没有使用整数,然后是很长的 switch 语句(switch (int), case 1: jPanel1.setIcon(null), case 2: jPanel2.setIcon(null)) 等),我不知道该使用哪种变量。

有没有更简单的方法来做到这一点(不仅仅是使用 switch 语句)?就像某种对象变量一样,我可以在其中存储一个摆动对象,然后稍后使用它来命令存储在其中的任何对象?任何人都知道怎么做我在说什么?帮助将不胜感激。

我处理鼠标点击事件的代码:

private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) { 

    if (pieceSelected == false) 
    { 
        pieceSelection = board[0][0]; 
        pieceSelected = true; 
    } else //if a piece was selected when this panel was clicked 
    { 
        //change this panel's icon to the icon of the first panel 
        jLabel1.setIcon(pieceSelection); 
        board[0][0] = pieceSelection; 

        //change the icon of the first square clicked to null 
        //the following part is the part i'm having trouble with 
        //board[last x coordinate][last y coordinate] = null; 
        //lastjPanel.setIcon(null) 

        pieceSelected = false; 
    } 
}

【问题讨论】:

标签: java swing icons jpanel mouse-listeners


【解决方案1】:

您应该创建一个大小为 [8][8] 的 jPanel 的二维数组,例如

JPanel[8][8] chessBoard = ...

而不是拥有

JPanel jPanel1...
JPanel jPanel2...
JPanel jPanel3...
JPanel jPanel4...
...

然后,您可以以相同的方式以编程方式访问所有 J​​Panel,而无需编写任何代码 64 次。你可以迭代、搜索等等。

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多