如何从java中的文本字段中获取数据并将其显示在第二种形式的jlabel中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21723541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:18:11  来源:igfitidea点击:

How to get data from a textfield in java and display it into a jlabel on the second form

javaswingjlabeljtextfield

提问by subas chandran

I was trying to build a simple java GUI application to get the data from the user and display it to the label.

我试图构建一个简单的 java GUI 应用程序来从用户那里获取数据并将其显示到标签上。

I got this code from the internet but it is using a separate pane for displaying the result.

我从互联网上得到了这段代码,但它使用一个单独的窗格来显示结果。

     import javax.swing.*;
     import java.awt.*;
     import java.awt.event.*;
     public class JTextFieldDemo extends JFrame {

//Class Declarations
JTextField jtfText1, jtfUneditableText;
String disp = "";
TextHandler handler = null;
//Constructor
public JTextFieldDemo() {
    super("TextField Test Demo");
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    jtfText1 = new JTextField(10);
    jtfUneditableText = new JTextField("Uneditable text field", 20);
    jtfUneditableText.setEditable(false);
    container.add(jtfText1);
    container.add(jtfUneditableText);
    handler = new TextHandler();
    jtfText1.addActionListener(handler);
    jtfUneditableText.addActionListener(handler);
    setSize(325, 100);
    setVisible(true);
}
//Inner Class TextHandler
private class TextHandler implements ActionListener {

            @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jtfText1) {
            disp = "text1 : " + e.getActionCommand();
        } else if (e.getSource() == jtfUneditableText) {
            disp = "text3 : " + e.getActionCommand();
        }
        JOptionPane.showMessageDialog(null, disp);
    }
}
//Main Program that starts Execution
public static void main(String args[]) {
    JTextFieldDemo test = new JTextFieldDemo();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

采纳答案by cafebabe1991

  1. Get the text from the TextField (textField).

    String text=textField.getText().toString();

  2. Now set it to the label using setTexton the JLabel.

    jlabel.setText(text);

  3. new SecondForm(jlabel,text).setVisible(true);

  1. 从 TextField ( textField) 中获取文本。

    String text=textField.getText().toString();

  2. 现在将其设置为使用setText上的标签JLabel

    jlabel.setText(text);

  3. new SecondForm(jlabel,text).setVisible(true);

If the Label exists on the next form say SecondForm. Skip Step2 and Do Step 3 after step 1

如果标签存在于下一个表单上,请说 SecondForm。跳过步骤 2 并在步骤 1 之后执行步骤 3

public class SecondForm  extends JFrame{


    public SecondForm(JLabel label,String text){

    label.setText(text); }

}