我正在编写一个基本的GUI应用程序,它涉及一个TextFields窗格,代表5种方法将字节输入到程序的缓冲区中。我们的想法是,当您编辑其中一个文本字段时,其他4个将使用您正在编辑的文本字段的已翻译值进行更新。例如,将十六进制字段更改为“FF”将使十进制字段立即更改为“255”,依此类推。
问题在于我无法弄清楚当更改一个时如何避免无限循环更新:十六进制字段被更改,这会修改十进制字段,然后再次尝试更新十六进制字段,依此类推,创建堆栈溢出错误。
以下是定义Fields及其侦听器的代码:
Score
如何更改此项以便编辑一个字段会更新其他字段一次而不是循环?感谢。
答案 0 :(得分:0)
原来我的lamba表达式实现了错误的类:InvalidationListener,它本应该使用ChangeListener:
Inputchar.textProperty().addListener((observable, oldValue, newValue) -> {
char[] cs = Inputchar.getText().toCharArray();
byte[] b = new byte[cs.length];
for (int i = 0; i < cs.length; i++) {
b[i] = (byte) cs[i];
}
BigInteger B = new BigInteger(b);
Inputhex.setText(B.toString(16));
Inputdec.setText(B.toString(10));
Inputoct.setText(B.toString(8));
Inputbin.setText(B.toString(2));
});
Inputhex.textProperty().addListener((observable, oldValue, newValue) -> {
BigInteger B = BigInteger.valueOf(Integer.parseInt(Inputhex.getText(), 16));
Inputchar.setText(BF_Program.bytestochars(B.toByteArray()));
Inputdec.setText(B.toString(10));
Inputoct.setText(B.toString(8));
Inputbin.setText(B.toString(2));
});
Inputdec.textProperty().addListener((observable, oldValue, newValue) -> {
BigInteger B = BigInteger.valueOf(Integer.parseInt(Inputdec.getText(), 10));
Inputchar.setText(BF_Program.bytestochars(B.toByteArray()));
Inputhex.setText(B.toString(16));
Inputoct.setText(B.toString(8));
Inputbin.setText(B.toString(2));
});
Inputoct.textProperty().addListener((observable, oldValue, newValue) -> {
BigInteger B = BigInteger.valueOf(Integer.parseInt(Inputoct.getText(), 8));
Inputchar.setText(BF_Program.bytestochars(B.toByteArray()));
Inputhex.setText(B.toString(16));
Inputdec.setText(B.toString(10));
Inputbin.setText(B.toString(2));
});
Inputbin.textProperty().addListener((observable, oldValue, newValue) -> {
BigInteger B = BigInteger.valueOf(Integer.parseInt(Inputbin.getText(), 2));
Inputchar.setText(BF_Program.bytestochars(B.toByteArray()));
Inputhex.setText(B.toString(16));
Inputdec.setText(B.toString(10));
Inputoct.setText(B.toString(8));
});
这个实际上有效。保持未来参考。