【问题标题】:Data assigned to new multidimensional array keeps updating分配给新多维数组的数据不断更新
【发布时间】:2021-08-30 23:42:42
【问题描述】:

对不起,我不知道这个问题的标题,但我在将数据分配给新的多维数组时遇到问题,做一些事情然后检索旧数据。

在我的例子中,我试图循环遍历 JTextFields,将所有当前数据专门分配给新的多维数组的颜色。然后我想进行搜索并更改找到的文本字段的背景颜色。

现在我有一个重置按钮,我希望将新多维数组中的旧颜色分配回字段。我遇到的问题是新的多维数组在搜索后使用新颜色进行了更新。如果有人能指出正确的方向,我真的很感激。

这是我的代码:

public JTextField[][] fields = new JTextField[totalX][totalY];
    public JTextField[][] newFields = new JTextField[totalX][totalY];
    
    if (e.getSource() == btnFind  || e.getSource() == txtSearch)
    {
        // Make a copy of fields before selecting everything
        for(int t = 0; t < totalX; t++){
            for(int r = 0; r < totalY; r++){
                newFields[t][r] = fields[t][r];
            }
        }
        
        findStudentRecord();
        // when looping though newFields[x][y] here it is already updated to the current colour
        
    }
    if (e.getSource() == btnReset)
    {
        for(int x = 0; x < totalX; x++){
            for(int y = 0; y < totalY; y++){
                fields[x][y].setText(newFields[x][y].getText());
                fields[x][y].setBackground(newFields[x][y].getBackground()); 
                // have tried this one but doesn't work
                if(newFields[x][y].getBackground() == Color.green){
                    fields[x][y].setBackground(Color.green);
                    System.out.print(fields[x][y].getText() + "\n");
                }
            }
        }
    } 

这里是 findStudentRecord()

public void findStudentRecord()
{
    boolean found = false;
    String strFind = txtSearch.getText();
    for(int x = 0; x < totalX; x++){
        for(int y = 0; y < totalY; y++){
            if(fields[x][y].getText().equalsIgnoreCase(strFind))
            {
                found = true;
            }
        }
    }
    if (found)
    {
        for (int x = 0; x < totalX; x++)
        {
            for(int y = 0; y < totalY; y++){
                if(fields[x][y].getText().equalsIgnoreCase(strFind))
                {
                    fields[x][y].setBackground(new Color(255,217,200));
                }
            }
        }
        txtSearch.setText(txtSearch.getText() + " ...Found.");
    }
    else
    {
        txtSearch.setText(txtSearch.getText() + " ...Not Found.");
    }
}

【问题讨论】:

  • 这不是 Java 的工作方式。 Java 不像 C/C++,你实际上并没有复制任何东西。 newFields[t][r]fields[t][r] 指向同一个对象。

标签: java arrays swing jtextfield


【解决方案1】:

您必须创建一个新的JTextField 并添加相关数据:

    newFields[t][r] = new javax.swing.JTextField();
    newFields[t][r].setText(fields[t][r].getText());
    newFields[t][r].setColumns(fields[t][r].getColumns());
    // any other property you want to transfer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    相关资源
    最近更新 更多