是否可以传递 JFrame 作为参数,然后我得到我创建的字段?
例如,我想从 JTextField 中获取值。在 JFrame 中,我可以使用简单的 txtField.getText() 来完成此操作,但是如何传递类似 JFrame 的参数呢?
static boolean validateFields(Webcrawler wc) {
try {
//I created the txtUrl in the original JFrame, I can take him there,
//but not here.
//The code is from the JFrame is generated by Netbeans.
wc.getTxtUrl().getText(); //<-- is something like this I want to do.
return true;
} catch (Exception e) {
return false;
}
}
By example, I want to take the value from an JTextField. In the JFrame I can do this with a simple txtField.getText()
, but how I do passing the JFrame like parameter?
static boolean validateFields(Webcrawler wc) {
try {
//I created the txtUrl in the original JFrame, I can take him there,
//but not here.
//The code is from the JFrame is generated by Netbeans.
wc.getTxtUrl().getText(); //<-- is something like this I want to do.
return true;
} catch (Exception e) {
return false;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有几种方法可以做您想做的事情。
1)公开您需要验证的文本字段。例如,从 JFrame 中公开 public TextField getUrlTextField() 。然后,在接受 JFrame 的验证方法中,您可以提取所有字段的文本。
不要这样做。您将验证逻辑与视图(JFrame)混合在一起。
相反,您应该使用 Controller 类作为视图(JFrame)和验证它的模型之间的中介。特别是,请了解 NetBeans Platform 如何使用 OptionsPanelController。这篇博客文章有一个很好的例子。
There are a few ways of doing what you want to do.
1) Expose the text fields you need to validate. e.g. expose public TextField getUrlTextField() from within your JFrame. Then within your validate method that accepts the JFrame, you can pull out the text of all of the fields.
DO NOT DO THIS. You're mixing the validation logic with the View (the JFrame).
Instead, you should use a Controller class that serves as an intermediary between your View (the JFrame) and the Model that is validating it. In particular, see how NetBeans Platform does its options panels using an OptionsPanelController. This blog post has a good example.
您的输入小部件(如 JTextFields)的成员变量很可能是私有的,因此无法从外部访问。
要么将它们声明为公共,要么为它们的值编写访问器函数。 (在您的 JFrame 中或从该 JFrame 派生的类中,如果它是由第三方创建的:
Most probably the member variables for your input widgets (like JTextFields) are private and hence inaccessible from the outside.
Either declare them public, or write accessor functions for their values. Something on the line of (inside your JFrame or a class derived from that JFrame if it is created by a third party:
您始终可以通过方法或(这里更有可能)构造函数参数将一个对象的引用传递给另一个对象。您还可以通过 SwingUtitlies 的 getWindowAncestor 方法获取对顶级窗口(此处为 JFrame)的引用。
但正如这里的答案(+1)中已经评论的那样,您似乎将程序逻辑与用户界面混合在一起,这可能不是您应该做的事情。
You could always pass a reference of once object to another via a method or (here more likely) a constructor parameter. You could also get a reference to the top-level Window (here your JFrame) via SwingUtitlies' getWindowAncestor method.
But as already commented on in an answer here (+1), you seem to be mixing program logic with user interface and that may not be something you should be doing.