【问题标题】:Run-time error for GUI calculator in JavaJava中GUI计算器的运行时错误
【发布时间】:2014-05-25 14:47:17
【问题描述】:

我正在使用 FlowLayout、GridLayout 和 BorderLayout 创建一个 GUI 计算器。我有以下代码。

import java.awt.*;
import javax.swing.*;
//Imports visual components for program
import java.awt.event.*;
//Imports functions for providing performing action on object

public class Calc extends JFrame implements ActionListener { 
    JPanel[] row = new JPanel[5];
//5 panels are created for 5 rows of buttons
 JButton[] button = new JButton[19];
String[] buttonString = {"1","2","3","+","4","5","6","-",
                     "7","8","9","*",".","/","C","rt","%",
                     "=", "0"};
double[] temporary = {0,0};
//Two memory locations for current number and upcoming number for signs such as *,/,%,+,-

boolean[] sign = new boolean[5];
//5 values for +,-,*,/,% are stored in array because they expect another number upon invocation 
JTextArea display = new JTextArea(1,10);
//Creates display with location specified 

    Calc(){
        //Constructor begins here
        setResizable(false);
        //Sets calculator size to be fixed at 380x250 
        //5x5 is created and selected for the calculator
        for(int a = 0; a < 5; a++)
            sign[a] = false;
        //Initialises the state of the signs for +,-,*,/,%

        JPanel displaypanel = new JPanel();
        JPanel first = new JPanel();
        JPanel last = new JPanel();
        //Create three panels for buttons to be placed in

        displaypanel.setLayout(new FlowLayout());
        displaypanel.add(display);
        //Display is added


        first.setLayout(new GridLayout(3,5));
        for(int a = 0; a<15; a++)
            first.add(button[a]);
        //"first" panel is added

        last.setLayout(new GridLayout(1,4));
        last.add(button[15]);
        last.add(button[16]);
        last.add(button[17]);
        last.add(button[18]);

        JFrame window = new JFrame("Task twelve");
        window.setLayout(new BorderLayout());
        window.add(displaypanel, BorderLayout.PAGE_START);
        window.add(first, BorderLayout.CENTER);
        window.add(last, BorderLayout.PAGE_END);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(400, 400);

        for(int a = 0; a < 19; a++){
            button[a] = new JButton();
            button[a].setText(buttonString[a]);
            button[a].addActionListener(this);
            //Assigns all the numbers and signs for the buttons
        }           
        for(int a = 0; a < 5; a++)
            row[a] = new JPanel();
        //Initialises JPanel for rows so they can be used

        //Assigns size for all buttons and display
        display.setEditable(false);         
    }
public void clear(){
    try{
        display.setText("");
        //Sets the display to be blank
        for(int a = 0; a < 5; a++)
            sign[a] = false;
            //Sets state of all signs to be false
        temporary[0] = 0;
        temporary[1] = 0;
        //Sets temporary values to be 0 as well
    } catch(NullPointerException e){
    }
}
public void root(){
    try{
        double temp = Math.sqrt(Double.parseDouble(display.getText()));
        //Creates variable that converts the value in display to a double and Sqroots the value
        display.setText(Double.toString(temp));
        //Converts value in temp to string and copies it to display
    } catch(NullPointerException e){
    }
}
public void getResult() {
    double result = 0;
    temporary[1] = Double.parseDouble(display.getText());
    String temp0 = Double.toString(temporary[0]);
    String temp1 = Double.toString(temporary[1]);
    try {
        if(temp0.contains("-")) {
            String[] temp2 = temp0.split("-", 2);
            temporary[0] = (Double.parseDouble(temp2[1]) * -1);
        }
        if(temp1.contains("-")) {
            String[] temp3 = temp1.split("-", 2);
            temporary[1] = (Double.parseDouble(temp3[1]) * -1);
        }
    } catch(ArrayIndexOutOfBoundsException e) {
    }
    try {
        if(sign[0] == true)
        //Addition sign
            result = temporary[0] + temporary[1];
         else if(sign[1] == true)
        //Subtraction sign
            result = temporary[0] - temporary[1];
        else if(sign[2] == true)
        //Multiplication sign
            result = temporary[0] * temporary[1];
        else if(sign[3] == true)
        //Division sign
            result = temporary[0] / temporary[1];
        else if(sign[4] == true)
        //Modulus sign
            result = temporary[0] % temporary[1];
        display.setText(Double.toString(result));

        for(int a = 0; a < 5; a++)
            sign[a] = false;
        //Sets state of all signs to be false after one of them has been invoked
    } catch(NumberFormatException e) {
    }
}
public void actionPerformed(ActionEvent ae){
    if(ae.getSource() == button[0])
        display.append("1");
    //When "1" is pressed, "1" is inserted to the display
    if(ae.getSource() == button[1])
        display.append("2");
    if(ae.getSource() == button[2])
        display.append("3");
    if(ae.getSource() == button[3]){
        //Addition sign is selected
        temporary[0] = Double.parseDouble(display.getText());
        sign[0] = true;
        display.setText("");
    }
    if(ae.getSource() == button[4])
        display.append("4");
    if(ae.getSource() == button[5])
        display.append("5");
    if(ae.getSource() == button[6])
        display.append("6");
    if(ae.getSource() == button[7]){
        //Subtraction sign is selected
        temporary[0] = Double.parseDouble(display.getText());
        sign[1] = true;
        display.setText("");
    }
    if(ae.getSource() == button[8])
        display.append("7");
    if(ae.getSource() == button[9])
        display.append("8");
    if(ae.getSource() == button[10])
        display.append("9");
    if(ae.getSource() == button[11]){
        //Multiplication sign is selected
        temporary[0] = Double.parseDouble(display.getText());
        sign[2] = true;
        display.setText("");
    }
    if(ae.getSource() == button[12])
        display.append(".");
    if(ae.getSource() == button[13]){
        //Division sign is selected
        temporary[0] = Double.parseDouble(display.getText());
        sign[3] = true;
        display.setText("");
    }
    if(ae.getSource() == button[14])
        clear();
    if(ae.getSource() == button[15])
        root();
    if(ae.getSource() == button[16]){
        //Modulus sign is selected
        temporary[0] = Double.parseDouble(display.getText());
        sign[4] = true;
        display.setText("");
    }
    if(ae.getSource() == button[17])
        getResult();
    if(ae.getSource() == button[18])
        display.append("0");        
}
public static void main(String[] args){
    Calc c = new Calc();
}
}

编译它不会导致任何错误。但是,运行课程确实如此。

Exception in thread"main" java.lang.NullPointerException
at java.awt.Container.addlmpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Calc.<init>(Calc.java:43)
at Calc.main(Calc.java:198)

我不明白这些错误,所以我不知道如何解决这个问题。有人可以帮忙吗?

【问题讨论】:

  • 捕捉 NPE 确实是个坏习惯。
  • 第 43 行是“Calc(){”。第 198 行是“Calc c = new Calc();”我的主要方法
  • @Pawal:同意 - 放弃那些捕获 - NPE 意味着你有错误的编码,最好是崩溃而不是瘫痪:pragmatictips.com/32

标签: java swing user-interface actionlistener calculator


【解决方案1】:

您在循环 button[a] = new JButton(buttonString[a]); 中创建了 15 个按钮,但随后您要求按钮 [15、16、...](您尚未创建的第 16、17... 按钮)并且为空。

【讨论】:

  • 抱歉,我在代码中找不到该行。可以给我指点一下吗?
  • @losertheone: last.add(button[15]); button[15] 为空
  • 知道了!我将按钮初始化循环重新定位到添加按钮并让计算器工作之前。谢谢!
猜你喜欢
  • 2012-12-26
  • 2015-05-12
  • 2011-10-31
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多