GUI应用程序显示然后立即退出

时间:2016-11-08 01:46:08

标签: java swing jframe

我们需要编写一个Java图形用户界面(GUI)应用程序,通过从用户那里获取要计算的表达式来进行整数运算。我的代码可以编译,但我不知道为什么它运行时会立即关闭。

这是我的CalculationGenerator.java

//using GUI to calculate 
 public class CalculationGenerator{
       public static void main(String[]args)
       {
        Calculator calculator = new Calculator();  
       }
    }

这是我的Calculator.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator extends JFrame
{
  private static final int FRAME_WIDTH = 400;  
  private static final int FRAME_HEIGHT = 300;

  private JLabel Label;
  private JTextField FIELD;
  private JButton button;
  private int result;

  public Calculator()
   {
      result = 0;
      Label = new JLabel("The result is:" +  result);

      createTextField();
      createButton();
      createPanel();

      setSize(FRAME_WIDTH, FRAME_HEIGHT);
   }
   //create text field
   private void createTextField()
   {
      Label = new JLabel("what do you want to calculate?");

      final int FIELD_WIDTH = 10;
      FIELD = new JTextField(FIELD_WIDTH);
      FIELD.setText("");
   }

   class GetResultListener implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
      try
         {
         Calculation();
         Label.setText("The result is:" +  result);
         }
      catch(NumberFormatException exception)
      {
         System.out.println("not an integer");
      }
      }
   }
   //calculate
   public void Calculation()
   {
   String s = FIELD.getText();
   String[]parts = s.split(" ");
   int x = Integer.parseInt(parts[0]);
   int y = Integer.parseInt(parts[2]);
   String operator = parts[1];

   switch(operator)
   {
   case"+":
      result = x + y;
      break;
   case"-":
      result = x - y;
      break;
   case"*":
      result = x * y;
      break;
   case"/":
      result = x / y;
      break;
   case"%":
      result = x % y;
      break;
   case"^":
      result = x ^ y; 
      break;

   }
   }
   private void createButton()
   {
   button = new JButton("get result");

   ActionListener listener = new GetResultListener();
   button.addActionListener(listener);

   }

   private void createPanel()
   {
      JPanel panel = new JPanel();
      panel.add(Label);
      panel.add(FIELD);
      panel.add(button);
      panel.add(Label);
      add(panel);
   }
}

1 个答案:

答案 0 :(得分:2)

初始化calculator后,您需要将JFrame设置为可见。

public class CalculationGenerator{
    public static void main(String[]args) {
        Calculator calculator = new Calculator();
        calculator.setVisible(true);
    }
}