简体   繁体   English

如何从JTextField到另一个JFrame中的JLabel获取文本?

[英]How to get text from JTextField to JLabel that is in another JFrame?

I am making an application in Netbeans and I would like to get the text from the jTextField and set it to a jLabel that is in another jFrame (not the same!) 我正在Netbeans中的一个应用程序,我想从一开始的文字jTextField并将其设置为一个jLabel是在另一个jFrame (不一样的!)

I did this: 我这样做:

jLabel.setText(jTextField1.getText());

But it doesn't work. 但这是行不通的。 And what event method should I use? 我应该使用哪种事件方法? actionPerformed ? actionPerformed

Forget about JFrames, forget about JTextFields and JLabels, but instead look at your question in its most basic essence which is: 忘掉JFrames,忘掉JTextFields和JLabels,而是以最基本的本质来看待您的问题:

I want to change the state of one object based on the state of another. 我想根据另一个对象的状态更改一个对象的状态。

That's it in a nutshell. 简而言之就是这样。

This can be easily solved by giving one class a getter/accessor method that extracts the desired information -- here the text in the JTextField, eg 通过给一个类一个提取所需信息的getter / accessor方法,可以很容易地解决此问题-这里是JTextField中的文本,例如

public String getFieldText() {
    return myTextField.getText();
}

and giving the other class a setter/mutator method that allows outside objects to inject the desired information, here to set the text of its JLabel 并给另一个类提供一个setter / mutator方法,该方法允许外部对象注入所需的信息,在此设置其JLabel的文本

public void setLabelText(String text) {
    myLabel.setTexzt(text);
}

The devil of course is when to call one or both of these methods, and where, and that will depend on much that you haven't told us, but likely one or both of these methods will be called in event code, such as in an ActionListener's actionPerformed method. 当然,魔鬼是什么时候调用这两个方法中的一个或两个,在何处调用,这将取决于您尚未告诉我们的很多内容,但是很可能在事件代码中调用这两个方法中的一个或两个,例如在一个ActionListener的actionPerformed方法。

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

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