简体   繁体   English

如何将变量数据从JFrame传递到另一个?

[英]How to pass variable data from a JFrame to another?

假设我在第1帧中有一个文本字段和一个按钮,当用户单击该按钮后,它将前进到下一帧并显示用户在第1帧中输入的内容。为了我。

Try the following: 请尝试以下操作:

Frame1.java
public class Frame1 extends JFrame{

    protected static Frame2 frame2;

    protected JTextField textField = new JTextField();
    protected JButton button = new JButton("Button");

    public Frame1() {

        JFrame Frame1 = new JFrame();
        Frame1.setBounds(0, 0, 200, 100);
        Frame1.setVisible(true);

        Frame1.add(textField, BorderLayout.NORTH);
        Frame1.add(button, BorderLayout.CENTER);

        button.addActionListener(
                newButtonListener(
                textField,frame2.textField));
    }


    public static void main(String[] args) {
        frame2 = new Frame2();
        new Frame1();       
    }
}

Frame2.java
public class Frame2 {

    protected JTextField textField = new JTextField();

    public Frame2() {

        JFrame Frame1 = new JFrame();
        Frame1.setBounds(200, 0, 200, 100);
        Frame1.setVisible(true);

        Frame1.add(textField, BorderLayout.CENTER);     
    }
}

ButtonListener.java
public class ButtonListener implements ActionListener{

    protected JTextField textField;
    protected JTextField textField2;

    public ButtonListener(JTextField textField, JTextField textField2) {
        this.textField = textField;
        this.textField2 = textField2;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Button")) {
            System.out.println(textField.getText());
            textField2.setText(textField.getText());
        }   
    }   
}

So you create a method which retrieves the value from the textfield when the button is clicked. 因此,您创建了一个方法,当单击按钮时,该方法将从文本字段中检索值。

public String getTextFieldValue(){
    return textField.getText();
}

Then create a Frame class that extends Frame and create a constructor that takes in the current frame or the string. 然后创建一个扩展Frame的Frame类,并创建一个接受当前框架或字符串的构造函数。 Then when you instantiate you pass in the frame or string. 然后,当您实例化时,您传入框架或字符串。 Boom, you have access to it. 繁荣,您有权使用它。

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

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