如何访问KeyListener中JTextField对象数组的对象?
我有这段代码,它使用包含 25 个元素的 JTextField 对象数组,我希望在更改或添加文本后,KeyListener (keyPressed) 会以不同的方式处理该元素。
那么如何将已更改字段的索引获取到侦听器中呢?
对于存在,第 10 个元素在用户添加或更改文本后会将字段的背景更改为绿色。
public JTextField field[];
public void TextFilling(){
field = new JTextField[25]; Font font = new Font("Times new Roman", Font.BOLD ,30);
textChangedListener listener = new textChangedListener();
//There are the process of formating size, location and other settings of the elements:
for (int i = 0, j=0, k=0; i< field.length; i++, k++) {field[i] = new JTextField();
if (k==j) field[i].setText("1");
if (i % 5 == 0 && i!=0) {j++; k = 0;}
field[i].setBounds(5+(100*(k+1)), 5+(100*(j+1)), 95, 95);
field[i].setHorizontalAlignment(JTextField.CENTER); field[i].setFont(font);
frame.add(field[i]);
field[i].addKeyListener(listener);
}
}
class textChangedListener implements KeyListener
{
public void keyPressed(KeyEvent e){
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要在文本组件上使用
KeyListener
,它没有帮助,而且您可能最终会处于状态突变的中间。相反,使用
DocumentListener
来监视文本字段的更改,请参阅 如何编写文档监听器了解更多详细信息。您还应该利用依赖注入,基本上将信息传递给需要与程序交互的类。
请参阅:
以获取更多信息。
我认为您即将面临的一件事是您如何共享和管理数据。
您想要花一些时间研究的一个概念是分离职责的方式。实现这一点的方法之一是通过“模型”。模型负责管理与数据关联的状态和规则。然后,视图负责呈现模型的当前状态并根据用户输入更新模型。
请参阅:
这个概念的关键要素之一是使用观察者模式。您已经在工作中看到了这一点,因为 Swing 侦听器是观察者。
哦,您真的非常想花时间学习和理解布局管理器 API。有关更多详细信息,请参阅在容器内布置组件
Don't use
KeyListener
on text components, it's not helpful and you might end up in the middle of mutation of the state.Instead, use a
DocumentListener
to monitor the changes to the text field, see How to Write a Document Listener for more details.You should also be making use of dependency injection, basically passing information to the classes which need to interact with your program.
See:
for more information.
One of the things I can see which is about to step up smack you then face, is how you share and manage data.
One concept you want to spend some time looking into, is the way you decouple your responsibilities. One of the ways this can be done is via a "model". A model is responsible for managing the state and rules associated with the data. The view then becomes responsible for presenting the current state of the model and updating the model based on the user input.
See:
One of the key elements to this concept is the use of the observer pattern. You've already seen this at work, as Swing listeners are observers.
Oh, and you really, really want to take the time and learn and understand the layout manager API. See Laying Out Components Within a Container for more details