简体   繁体   中英

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. Then when you instantiate you pass in the frame or string. Boom, you have access to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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