如何解决分配给新多维数组的数据不断更新
抱歉,我不知道这个问题的标题是什么,但我在将数据分配给新的多维数组时遇到问题,请执行某些操作然后检索旧数据。
在我的例子中,我试图遍历 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.");
}
}
解决方法
您必须创建一个新的 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。