公共类中的值未从私有空中的操作更新

时间:2018-01-31 10:55:16

标签: java swing

我有以下代码:

public class GUI extends javax.swing.JFrame {
    int Num1;
    int Num2;
    int Num3;

    private void saveNumMouseClicked(java.awt.event.MouseEvent evt) {                                       
        Num1 = Integer.parseInt(Field1.getText());
        Num2 = Integer.parseInt(Field2.getText());
        Num3 = Integer.parseInt(Field3.getText());
    }
}

然后,我尝试通过执行以下操作在不同的JFrame中显示这些值:

public jrame2() {
    initComponents();
    GUI Class = new GUI();
    lblValue.setText(String.valueOf(Class.Num1));
}

这只显示最初声明为Num1的值(在本例中为0)而不是我使用textfield更新值的值。
将不胜感激任何帮助。谢谢:))

1 个答案:

答案 0 :(得分:0)

使用DocumentListener界面。以下是完整的功能代码。希望它会有用:

import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Main {

    public static void main(String[] args) 
    {
        new GUI();
    }

}


class GUI extends javax.swing.JFrame 
{
    int Num1;
    int Num2;
    int Num3;

    JTextField Field1;
    JTextField Field2;
    JTextField Field3;
    JLabel lblValue;

    GUI()
    {
        DocumentListener dl = new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent arg0) {
                setChanges();
            }

            @Override
            public void insertUpdate(DocumentEvent arg0) {
                setChanges();

            }

            @Override
            public void changedUpdate(DocumentEvent arg0) {
                setChanges();
            }

            void setChanges()
            {
                saveNumMouseClicked();
                lblValue.setText(String.valueOf(Num1));
            }
        };
        Field1 = new JTextField("JTextField 1: ");
        Field2 = new JTextField("JTextField 2: ");
        Field3 = new JTextField("JTextField 3: ");
        lblValue = new JLabel("Change");

        Field1.getDocument().addDocumentListener(dl);
        Field2.getDocument().addDocumentListener(dl);
        Field3.getDocument().addDocumentListener(dl);

        this.setLayout(new FlowLayout());
        this.add(Field1);
        this.add(Field2);
        this.add(Field3);
        this.add(lblValue);
        this.setVisible(true);
        this.setBounds(10, 10, 300, 300);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void saveNumMouseClicked() {                                       
        Num1 = tryToGetInt(Field1);
        Num2 = tryToGetInt(Field2);
        Num3 = tryToGetInt(Field3);
    }

    private int tryToGetInt(JTextField tf)
    {
        int res = 0;
        try
        {
            res = Integer.parseInt(tf.getText());
        }
        catch(Exception ex) {}
        return res;
    }
}