1
我們需要編寫一個Java圖形用戶界面(GUI)應用程序,通過從用戶獲取要計算的表達式來完成整數算術。我的代碼可以編譯,但我不知道爲什麼當它運行時立即關閉。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);
}
}
您沒有使JFrame可見。 'calculator.setVisible(true);'應該在初始化'計算器之後。 –
謝謝!有用! – Lenox
@Matthew:你能否將你的評論形成一個答案?否則,這個問題顯示爲「未回答」... – Igor