从另一个类设置JTextField

时间:2018-11-21 23:50:24

标签: java

在从另一个类设置JTextField时遇到问题。当我按下按钮“ =”时,应该在AddNumbers类内进行计算并将JTextField设置为计算结果。但是现在它抛出NullPointerException。我不知道如何设置JTextField。由于责任链设计,我必须在AddNumbers中设置它。

public class AddNumbers implements Chain {
private Chain nextInChain;
public CalcGui calcgui;
int result=0;

@Override
public void setNextChain(Chain nextChain) {
    // TODO Auto-generated method stub
    this.nextInChain=nextChain;
}

@Override
public void calculate(Numbers request) {
    // TODO Auto-generated method stub
    if(request.GetCalcWanted()=="add") {
        result = request.GetNumber1()+ request.GetNumber2();
        this.calcgui.txtWynik.setText(String.valueOf(result)); //NULLPOINTER
    }else {
        nextInChain.calculate(request);
    }
}

这是CalcGui类

public class CalcGui {

private JFrame frame;
JTextField txtWynik; 
static Numbers request;
int x,y;
String operation;
boolean clicked = false;
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                CalcGui window = new CalcGui();
                window.frame.setVisible(true);


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public CalcGui() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 270, 361);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    txtWynik =new JTextField();
    Chain chainCalc1=new AddNumbers();    
    JButton btneq = new JButton("=");
    btneq.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            request = new Numbers(x,y,operation);
            chainCalc1.calculate(request);

        }
    });

1 个答案:

答案 0 :(得分:-3)

我会给你一个想法,这种方法:

 if (answerItems.value != null && answerItems.value.HasValues && answerItems.value["id"]!=null)
                {

可以收到对您的JTextField的引用,如下所示:

public void calculate(Numbers request) {

我认为这可以解决您的NPE问题。

干杯

-杆