Java 获取 JPanel 组件 [英] Java get JPanel Components

查看:25
本文介绍了Java 获取 JPanel 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JPanel,里面装满了 JTextFields...

I have a JPanel full of JTextFields...

for (int i=0; i<maxPoints; i++) {
    JTextField textField = new JTextField();
    points.add(textField);
}

我以后如何在该 JPanel 中获取 JTextField?就像我想要他们的价值观一样

How do I later get the JTextFields in that JPanel? Like if I want their values with

TextField.getText();

谢谢

推荐答案

请记住,他们自己并没有到达那里(我想阅读一些关于在运行时动态创建这些面板的问题)

Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime )

在那张贴的答案中,有人说您应该在数组中保留对这些文本字段的引用.这正是您需要的:

In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here:

List<JTextField> list = new ArrayLists<JTextField>();

// your code...
for (int i=0; i<maxPoints; i++) { 
    JTextField textField = new JTextField();
    points.add(textField);
    list.add( textField ); // keep a reference to those fields.
}

//稍后

for( JTextField f : list ) { 
   System.out.println( f.getText() ) ;
}

不是那么容易吗?

请记住将这些类型的工件 ( list ) 尽可能保密.它们仅供您控制,我认为它们不属于界面.

Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don't think they belong to the interface.

假设您想要获取文本数组,而不是

Let's say you want to get the array of texts, instead of

 public List<JTextField> getFields();

你应该考虑:

 public List<String> getTexts(); // get them from the textfields ... 

这篇关于Java 获取 JPanel 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆