简体   繁体   English

用Java动态定义事件处理程序

[英]Define dynamically event handler in Java

Assume that I have defined two arrays in Java. 假设我已经用Java定义了两个数组。 The first array has m cells and the second has n cells. 第一个数组有m单元,第二个数组有n单元。 Assume that each cells can have a 0 or 1 value. 假设每个单元格可以具有01值。

In this program every cell of the first array will join one of the cells of the second array, but we do not know which one will be connected to which cell of the second array (This connection is totally logical,eg we just know array1[3] is related to array2[7] ). 在此程序中,第一个数组的每个单元将加入第二个数组的一个单元,但是我们不知道哪个将连接到第二个数组的哪个单元(这种连接是完全逻辑的,例如,我们只知道array1[3]array2[7]有关。

So now I want to define an event handler for each of these relationship, so when one of the cells fluctuate from 1 to 0, its paired cell fluctuate. 因此,现在我想为每个关系定义一个事件处理程序,这样,当一个单元从1到0波动时,其成对的单元就会波动。 Actually I want to define event handler in a run-time and in dynamic way, because before it, I do not know which one of the cells in array1 will be pair with which one of cells in array2 . 实际上,我想以运行时动态方式定义事件处理程序,因为在此之前,我不知道array1哪个单元将与array2哪个单元配对。

Is there any solution for this? 有什么解决办法吗?

If you think I can solve this problem without dynamic event handler please let me know about your solution. 如果您认为没有动态事件处理程序就可以解决此问题,请告诉我您的解决方案。

Here's a way to solve this without using an event handler. 这是一种无需使用事件处理程序即可解决此问题的方法。 See if this works for what you are doing. 看看这是否适合您的工作。

First, instead of two arrays, let's use two 2D arrays that are mx 1 and nx 1 . 首先,让我们使用两个分别为mx 1nx 1 2D数组,而不是两个数组。

int[][] array1 = new int[m][];
int[][] array2 = new int[n][];
for (int i = 0; i < m; i++)
    array1[i] = new int[] { /* your code */ ? 1 : 0 };
for (int i = 0; i < n; i++)
    array2[i] = array1[ /* your code */ ];

The first /* your code */ is your condition for choosing to put either 1 or 0 into each element of array1 . 第一个/* your code */是选择将10放入array1每个元素中的条件。 The second /* your code */ is your method for deciding which element of array1 corresponds to each element of array2 . 第二个/* your code */是您用来确定array1哪个元素对应于array2每个元素的方法。

Now each element in array2 is also an element of array1 , so when you update a value in one of the arrays from 0 to 1 , it is also updated in the other array. 现在, array2每个元素也是array1的元素,因此,当您将一个数组中的值从0更新为1 ,它也会在另一个数组中更新。

array2[7] = array1[3];
array1[3][0] = 0;
System.out.println(array2[7][0]); // prints "0"
array1[3][0] = 1;
System.out.println(array2[7][0]); // prints "1"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM