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

时间:2015-04-29 14:49:16

标签: java

假设我在第1帧中有一个文本字段和一个按钮,在用户点击该按钮后,它将进入下一帧并显示用户在第1帧中输入的内容。我已搜索网络和非它对我有用。

2 个答案:

答案 0 :(得分:6)

尝试以下方法:

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());
        }   
    }   
}

答案 1 :(得分:0)

因此,您创建了一个方法,该方法在单击按钮时从文本字段中检索值。

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

然后创建一个Frame类,该类扩展Frame并创建一个接受当前帧或字符串的构造函数。然后在实例化时传入帧或字符串。热潮,你可以访问它。