Reputation:
This program written in java serves as a calculator. Can anyone tell me how to implement a try/catch block if the user tries to input from the result text so that I can handle incorrect workflow?
Here is the code:
package simplecal;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleCal extends JFrame {
JTextField jftinput1, jftinput2, jftresult;
JButton jbtminus, jbtadd,jbtdivid, jbttimes;
final int JTEXT_SIZE = 5;
SimpleCal(){
setLayout(new FlowLayout());
jftinput1 = new JTextField(JTEXT_SIZE);
jftinput2 = new JTextField(JTEXT_SIZE);
jftresult = new JTextField(JTEXT_SIZE);
add(new JLabel("Input 1: "));
add(jftinput1);
add(new JLabel("Input 2: "));
add(jftinput2);
add(new JLabel("Result "));
add(jftresult);
JPanel p1 = new JPanel();
jbtminus = new JButton("Subtract");
jbtadd = new JButton("Add");
jbttimes = new JButton("Multiple");
jbtdivid = new JButton("Divided");
p1.add(jbtminus);
jbtminus.addActionListener(new ButtonListener1());
p1.add(jbtadd);
jbtadd.addActionListener(new ButtonListener2());
p1.add(jbttimes);
jbttimes.addActionListener(new ButtonListener3());
p1.add(jbtdivid);
jbtdivid.addActionListener(new ButtonListener4());
add(p1, BorderLayout.SOUTH);
}
class ButtonListener1 implements ActionListener{
public void actionPerformed(ActionEvent e){
double input1 = Double.parseDouble(jftinput1.getText());
double input2 = Double.parseDouble(jftinput2.getText());
double answer = input1 - input2;
jftresult.setText(Double.toString(answer));
}
}
class ButtonListener2 implements ActionListener{
public void actionPerformed(ActionEvent e){
double input1 = Double.parseDouble(jftinput1.getText());
double input2 = Double.parseDouble(jftinput2.getText());
double answer = input1 + input2;
jftresult.setText(Double.toString(answer));
}
}
class ButtonListener3 implements ActionListener{
public void actionPerformed(ActionEvent e){
double input1 = Double.parseDouble(jftinput1.getText());
double input2 = Double.parseDouble(jftinput2.getText());
double answer = input1 * input2;
jftresult.setText(Double.toString(answer));
}
}
class ButtonListener4 implements ActionListener{
public void actionPerformed(ActionEvent e){
double input1 = Double.parseDouble(jftinput1.getText());
double input2 = Double.parseDouble(jftinput2.getText());
double answer = input1 / input2;
jftresult.setText(Double.toString(answer));
}
}
public static void main(String[] args) {
SimpleCal frame = new SimpleCal();
frame.setTitle("Simple Cal");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(450,100);
}
}
Upvotes: 0
Views: 557
Reputation: 994947
You don't need an exception handler for this. Simply set the field to not editable:
jftresult.setEditable(false);
See http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#setEditable(boolean).
Upvotes: 1