Reputation: 11
We need to write a Java Graphical User Interface (GUI) application program to do integer arithmetic by obtaining from the user an expression that is to be calculated. My code can compile, but I don't know why when it runs that it shuts down immediately.
This is my CalculationGenerator.java
:
//using GUI to calculate
public class CalculationGenerator{
public static void main(String[]args)
{
Calculator calculator = new Calculator();
}
}
This is my 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);
}
}
Upvotes: 1
Views: 58
Reputation: 1525
You need to set your JFrame as visible after you initialize calculator
.
public class CalculationGenerator{
public static void main(String[]args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
}
}
Upvotes: 2