I have a school project where we need to create a program to convert a number into binary but i cant seem to get them to work together. they will compile but wont actually get out the right answer my toString() method works it just isin't getting the decimal the user entered or the binary from the convertToBinary so i'm not sure where it is failing. Any Help would be great. Driver and Method below! thanks!
Driver:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class DecimalConverter extends JPanel{
//Sets up the Window
public DecimalConverter(){
JFrame window = new JFrame("Binary To Decimal");
//exit program when window closes
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//WINDOW COMPONENETS:
JLabel lblPrompt = new JLabel("Enter your number to convert: ");
JLabel lblBinary = new JLabel("Binary: ");
JTextField txtDecimal = new JTextField();
JButton btnToBinary = new JButton("To Binary");
//SET POSITIONS
lblPrompt.setBounds(40, 40, 200, 30);
txtDecimal.setBounds(250, 40, 100, 30);
lblBinary.setBounds(40, 80, 300, 30);
btnToBinary.setBounds(250, 120, 100, 30);
setLayout(null);
add(lblPrompt);
add(txtDecimal);
add(lblBinary);
add(btnToBinary);
window.add(this);
window.setSize(400, 200);
window.setVisible(true);
//Event for button
btnToBinary.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String str = txtDecimal.getText();
DecimalBinary b = new DecimalBinary();
lblBinary.setText(b.toString());
}//ends Action Performed
}//Ends ActionListener
);//End Event
}//End Constructor
public static void main(String args[]){
new DecimalConverter();
}//ends main
}//End Class
Method:
class DecimalBinary{
private String decimal = "0";
private String binary = "";
private int dec;
public void setDecimal(String decimal){
int dec = Integer.parseInt(decimal);
convertToBinary(dec);
}
public String convertToBinary(int dec){
int pow = 128;
while (dec > 0){
if (dec >= pow){
binary += "1";
dec = dec - pow;
}
else if (dec < pow){
binary += "0";
}
pow = pow / 2;
}
return decimal;
}
public String toString(){
return decimal + " is " + binary + " in binary";
}
}
Change your code as follows (// added)
public void setDecimal(String decimal){
this.decimal = decimal // added
int dec = Integer.parseInt(decimal);
convertToBinary(dec);
}
public void actionPerformed(ActionEvent e){
String str = txtDecimal.getText();
DecimalBinary b = new DecimalBinary();
b.setDecimal(str) // added
lblBinary.setText(b.toString());
}//ends Action Performed
Related
I made this program where you can input a string and it will record it and display back to the user the amount of characters in that string and the number of strings entered. For example, if the user types in "Sally" into the text box and clicks the button, it will say the
Number of string: 1
Number of characters: 5
And the user can input more strings if they want, like "Alex" and that will change the number from 1 string to 2 and the number of characters to 9
Anyway I want to make it so there is a second text box where the user can type in a few characters and search for those characters to see how many strings entered previously by the user contains the characters searched by the user
Here is an example of what it should do:
So if the user inputs: "Sally", 'Jack", and "Dachshunds" the program should read back saying that there are 3 strings and 20 characters.
Now if the user types "ac" into the search box, the program will say "The number of strings with 'ac' is 2
(Strings Jack and Dachshunds contain 'ac')
Here is my code for the entire program if what I said above was confusing
I just need help on how to code the part for searching for specific characters in those strings
I know there is something called get.contains() but I tried to implement it and I was having trouble with it
import javax.swing.*;
import java.awt.event.*;
public class good{
StringSet sSet;
JTextField inputStr;
JLabel numStr;
JLabel numChar;
JTextField inputStr2;
JLabel numofStr;
good() {
sSet=new StringSet();
JFrame f= new JFrame("StringSetYetAgain");
JLabel en=new JLabel("Enter a String:");
en.setBounds(50, 10, 100, 100);
numStr=new JLabel("Number of Strings: 0");
numStr.setBounds(50, 160, 400, 100);
numChar=new JLabel("Number of Characters: 0");
numChar.setBounds(50, 180, 400, 100);
inputStr=new JTextField();
inputStr.setBounds(50, 80, 400, 50);
JButton pushMe=new JButton("Push to include String");
pushMe.setBounds(50, 140, 400, 50);
JLabel enter=new JLabel("String to search for:");
enter.setBounds(50, 230, 400, 100);
inputStr2=new JTextField();
inputStr2.setBounds(50, 300, 400, 50);
JButton pushMe2=new JButton("Search");
pushMe2.setBounds(50, 360, 400, 50);
numofStr=new JLabel("Number of strings with: 0");
numofStr.setBounds(50, 405, 400, 50);
pushMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s=inputStr.getText();
sSet.add(s);
String ns=numStr.getText();
ns=ns.substring(0, ns.length() - 1)+sSet.size();
numStr.setText(ns);
String nc=numChar.getText();
nc=nc.substring(0, nc.length() - 1)+sSet.numChars();
numChar.setText(nc);
inputStr.setText("");
}
});
//I would add the code for the search part here
f.add(en);
f.add(inputStr);
f.add(pushMe);
f.add(numStr);
f.add(numChar);
f.add(enter);
f.add(inputStr2);
f.add(pushMe2);
f.add(numofStr);
f.setSize(550,600);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new good();
}
}
Here is the source code for the StringSet class
public class StringSet {
private String[] arr;
private int count;
public StringSet() {
arr = new String[200];
count = 0;
}
void add(String newStr){
arr[count++] = newStr;
}
int size(){
return count;
}
int numChars(){
int total = 0;
for(int i = 0; i < count; ++i){
total += arr[i].length();
}
return total;
}
int countStrings(int len){
int total = 0;
for(int i = 0; i < count; ++i){
if(arr[i].length() == len)
++total;
}
return total;
}
}
Here is the part so far for the searching of the characters
pushMe2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
public int countOf(String substring, StringSet sSet) {
int counter = 0;
for (int i = 0; i < sSet.size(); i++)
if (sSet.get(i).contains(substring))
counter++;
return counter;
}
}
});
Add that where you said
I would add the code for the search part here
buttonThatShouldCount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int counter = 0;
String substring = inputStr2.getText();
for (int i = 0; i < sSet.size(); i++)
if (sSet.get(i).contains(substring))
counter++;
inputStr2.setText("The substring \"" + substring "\" occurs " + count + " times.");
}
}
You'll also need to add the following method to your StringSet class:
public String get(int index) {
return arr[index];
}
We need to do this, because otherwise there is no way to access the strings stored in the set.
If user enters anything other than 0-9 or + - / * in the JtextField then a JOptionPane display error to user.
I seen a few different ways of potentially doing this...
Maybe a documentListener or a Inputverifyer.
Main Class
package p2gui;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.*;
import javax.swing.JOptionPane;
/**
*
*
*/
public class P2GUI extends JFrame implements ActionListener {
JFrame f = new JFrame("Three Address Generator");// Title
private final JButton evaluate;
private final JLabel textfieldLabel;
private final JTextField entryField;
private final JLabel resutfieldlabel;
private final JTextField resultField;
private final JOptionPane popup = new JOptionPane();
public void display() {
setVisible(true);
}
P2GUI() {
f.setSize(425, 180);//450 width and 525 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible //window size
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textfieldLabel = new JLabel("Enter Postfix Expression");
f.add(textfieldLabel);
textfieldLabel.setBounds(10, 10, 160, 25);
entryField = new JTextField("");
entryField.addActionListener(this);//ActionListener
f.add(entryField);
entryField.setBounds(160, 10, 220, 25);
evaluate = new JButton("Construct Tree");//creating instance of JButton
evaluate.addActionListener(this);//ActionListener
f.add(evaluate);
evaluate.setBounds(137, 55, 130, 30);
resutfieldlabel = new JLabel(" Infix Expression ");
f.add(resutfieldlabel);
resutfieldlabel.setBounds(20, 100, 100, 25);
resultField = new JTextField("");
resultField.addActionListener(this);//ActionListener
resultField.setEditable(false);
f.add(resultField);
resultField.setBounds(125, 100, 220, 25);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == evaluate) {
String fullString = entryField.getText().trim();
if (fullString.matches("\\d+") || fullString.matches("[-+*/]")) {
Convert conversion = new Convert();
resultField.setText(conversion.convert(fullString));
eraseTextField();
}else {
JOptionPane.showMessageDialog(null,"Wrong input enter a digit or
arithmetic operator");
eraseTextField();
}
}
}
public void eraseTextField() {
entryField.setText("");
entryField.requestFocus();
}
public static void main(String[] args) {
P2GUI p1GUI;
p1GUI = new P2GUI();
}
}
Convert. java class
package p2gui;
import java.util.Stack;
/**
*
* #author Mike
*/
public class Convert {
/**
* Checks if the input is operator or not
*
* #param c input to be checked
* #return true if operator
*/
private boolean operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
/**
* Converts any postfix to infix
*
* #param postfix String expression to be converted
* #return String infix expression produced
*/
public String convert(String postfix) {
Stack<String> s = new Stack<>();
for (int i = 0; i < postfix.length(); i++) {
char c = postfix.charAt(i);
if (operator(c)) {
String b = s.pop();
String a = s.pop();
s.push("(" + a + c + b + ")");
} else {
s.push("" + c);
}
}
return s.pop();
}
}
You can use regex to solve your problem, here is a simple example you can use it to solve your problem :
String str = "123";
if (str.matches("\\d+")) {
JOptionPane.showMessageDialog(null, "Degit");
} else if (str.matches("[-+*/]")) {
JOptionPane.showMessageDialog(null, "arithmetic operator( + - * /)");
}else{
JOptionPane.showMessageDialog(null, "Incorrect input");
}
Explication
str.matches("[-+*/]") if your input is - + * or / then it will return true.
str.matches("\\d+") if your input is a number then it will return true
You can use String.matches() to validate the expression entered by the user.
So basic code for this :
String expression = "9+45-3/5*9"; //store expression here from text-field.
boolean isvalid = expression.matches("[0-9-+*/]+");
if(isvalid)
JOptionPane.showMessageDialog(null,"Valid Expression!");
else
JOptionPane.showMessageDialog(null,"Not Valid Expression!");
Still here you need to check other requirements that no two operators comes continuously and other stuff as well.
I made a program that has a JFrame that contains a JTextField, a button, and two JLabels. When a number is typed into the JTextField, either pressing the enter key or clicking on the JButton should display the number in scientific notation on the second JLabel. When I hit the enter key, it works, however, when I click on the JButton, it does not. It gives me a NumberFormatException: empty string.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyMath extends JPanel implements ActionListener
{
private JTextField textField;
private static JLabel textArea;
private static JLabel comment;
private JButton button;
private static JFrame frame;
public MyMath()
{
comment = new JLabel("Enter a number");
textField = new JTextField();
textField.setSize(new Dimension(10 , 10));
textField.addActionListener(this);
button = new JButton("Go");
button.addActionListener(this);
}
public static void addComponentsToPane(Container pane)
{
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new MyMath().textField);
pane.add(new MyMath().button);
pane.add(new MyMath().comment);
pane.add(textArea);
}
public void actionPerformed(ActionEvent evt)
{
String text = textField.getText();
textArea.setText(SciNotation.convertToSciNotation(text));
textArea.setHorizontalAlignment(SwingConstants.CENTER);
comment.setText(text + " in Scientific Notation:");
textField.selectAll();
}
private static void createAndShowGUI()
{
frame = new JFrame("Scientific Notation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
Container bg = frame.getContentPane();
Dimension d = new Dimension(300, 150);
bg.setPreferredSize(d);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GREEN);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Point screenCenter = new Point (screen.width/2 , screen.height/2);
Point center = new Point(screenCenter.x - (150), screenCenter.y - (75));
frame.setLocation(center);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Here is SciNotation.java
import java.awt.Component;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
public class SciNotation
{
public static String convertToSciNotation(String num)
{
num = num.replaceAll("," , "");
if (num.contains("E")) //not working
{
String[] partsE = num.split("E");
String beforeE = partsE[0];
String afterE = partsE[1];
char first = num.charAt(0);
num = first + beforeE;
}
double number = Double.parseDouble(num);
double resultNumber = 0;
int power = 0;
String numString = Double.toString(number);
String[] parts = numString.split("\\.");
String decimals = parts[1];
int decimalInt = Integer.parseInt(decimals);
int numberInt = (int) number;
if(number > -1 && number < 1)
{
String[] low = numString.split("\\.");
String afterLow = low[1];
for(int i = 1; i < 10; i++)
{
String decNums = Integer.toString(i);
afterLow = afterLow.replaceAll(decNums, "");
int zeros = afterLow.length();
power = -1 * (zeros + 1);
resultNumber = number * Math.pow(10, zeros + 1);
decimals = "";
}
}
if(decimalInt == 0)
{
decimals = "";
}
if( number >= 10)
{
power = Integer.toString(numberInt).length() - 1;
resultNumber = numberInt/(Math.pow(10,(power)));
}
if((number >= 1 && number < 10) || (number <= -1 && number > -10))
{
resultNumber = number;
decimals = "";
}
if(number <= -10)
{
power = Integer.toString(numberInt).length() - 2;
resultNumber = numberInt/(Math.pow(10,(power)));
}
return resultNumber + decimals + " x 10^" + power;
}
}
This bug is pretty tricky. You constructed three MyMath instances. So your code was holding a wrong reference to your JTextFiled instance. That's why you couldn't get the right input.
public static void addComponentsToPane(Container pane) {
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new MyMath().textField); //MyMath instance 1
pane.add(new MyMath().button); //MyMath instance 2
pane.add(new MyMath().comment); //MyMath instance 3
pane.add(textArea);
}
Here is the right code:
public static void addComponentsToPane(Container pane) {
MyMath myMath = new MyMath();
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(myMath.textField);
pane.add(myMath.button);
pane.add(myMath.comment);
pane.add(textArea);
}
:)
I'm learning to program in Java and I'm creating my first GUI App. It about creating 100 random numbers. I did it first on cmd like this:
public class RandomNumbers {
public static void main(String[] args){
float n = 100;
float m = 1513;
float a = 19713;
float x = 177963;
float c = 1397;
float r;
float i;
for(i=0;i<=n;i++){
r = (a*x+c)%m;
x = r;
r = r/m;
System.out.println(r);
}
}
}
For some reason when i try to print the 100 random numbers on a text area, it only prints me one.This is the code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GUIRandomNumbers extends JFrame implements ActionListener{
public JTextArea area;
public JScrollPane scroll;
public JButton button;
public RandomNumbers(){
setLayout(null);
area = new JTextArea();
area.setEditable(false);
scroll = new JScrollPane(area);
scroll.setBounds(10, 10, 400, 300);
add(scroll);
button = new JButton("Generate");
button.setBounds(10, 650, 100, 25);
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
float n = 100;
float m = 1513;
float a = 19713;
float x = 177963;
float c = 1397;
float r;
float i;
if(e.getSource()==button){
for(i=0;i<=n;i++){
r = (a*x+c)%m;
x = r;
r = r/m;
area.setText(String.valueOf(r));
}
}
}
public static void main(String[] args) {
RandomNumbers p1 = new RandomNumbers();
p1.setBounds(0, 0, 500, 750);
p1.setVisible(true);
}
}
What could be the problem? I will really appreciae your help.
Thanks in advance.
when you do
area.setText(String.valueOf(r));
it overwrites the text on the text area with the new text.
you should use
area.append(String);
method instead.
Use this
area.append(String.valueOf(r) + "\n\r");
instead of
area.setText(String.valueOf(r));
setText(String) method replace the previous text. Use area.append(String) method.
Accordint to docs
Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.
At first I suppose that you mean
GUIRandomNumbers p1 = new GUIRandomNumbers();
The reason that makes you see only one number is that one number is written above the other.
I mean that you write 100 times a random number in the textArea!
area.append("text");
is the method that will do your job!
I am writing a Mortgage Calculator for class and I have it working the way I need it to, except everytime I click the "Calculate" button it will just continue to add to the table instead of the table clearing and showing new values. I know my code might look a little sloppy and I have some things commented out that don't need to be there because I'm still working it, but do you have any suggestions?
FYI I am still a beginner learning Java and it has taken me over 20hrs to get this far (and i"m pretty proud of myself!) Thank you!!
//Import all required Packages
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.*;
import java.awt.event.*;
public class MortgageCalculator extends JFrame implements ActionListener {
// Loan Values
double intPrincipal, interestRate, calcPayment, monthlyInterest, currentInterest, principalPaid, newBalance;
int totalMonths;
double[] loanInterest = {5.35, 5.5, 5.75}; // Yearly interest in decimal form
int[] loanTerm = {7, 15, 30}; // Total months of term
String principal;
String comboArray[] = {"7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%"};
int termYears, termMonths, done, i=0, m=0, p=0;
//Set up panels
JPanel contentPanel;
//Set up labels
JLabel mortgageLabel, paymentLabel, termLabel;
//Set up buttons
JButton calculateButton, clearButton, exitButton;
//TextFields
JTextField txtMortgage = new JTextField(10);
JTextField txtPayment = new JTextField(10);
//New Text Area
JTextArea textarea = new JTextArea();
DecimalFormat df = new DecimalFormat("$###,###.00"); //Formatting the results to decimal form
//Combo Box
JComboBox loansList = new JComboBox();
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
//Build GUI
public MortgageCalculator()
{
super();
initializeContent();
}
public void initializeContent()
{
this.setSize(700, 500);
this.setLocation(0, 0);
this.setContentPane(contentPanel());
this.setTitle("Mortgage Calculator");
}
public JPanel contentPanel()
{
contentPanel = new JPanel();
contentPanel.setLayout(null);
//Add labels to the panel
mortgageLabel = new JLabel("Mortgage:");
mortgageLabel.setLocation(200, 30);
mortgageLabel.setSize(100, 25);
contentPanel.add(mortgageLabel);
termLabel = new JLabel("Term & Rate:");
termLabel.setLocation(183, 55);
termLabel.setSize(100, 30);
contentPanel.add(termLabel);
paymentLabel = new JLabel("Monthly Payment:");
paymentLabel.setLocation(158, 85);
paymentLabel.setSize(100, 30);
contentPanel.add(paymentLabel);
//Text Fields
txtMortgage = new JTextField(10);
txtMortgage.setLocation(280, 30);
txtMortgage.setSize(150, 25);
contentPanel.add(txtMortgage);
txtPayment = new JTextField(10);
txtPayment.setLocation(280, 85);
txtPayment.setSize(150, 25);
contentPanel.add(txtPayment);
//Combo Box
loansList.addItem(comboArray[0]);
loansList.addItem(comboArray[1]);
loansList.addItem(comboArray[2]);
loansList.setLocation(280, 55);
loansList.setSize(150, 25);
loansList.addActionListener(this);
contentPanel.add(loansList);
//textarea.setPreferredSize(new Dimension(650, 300));
//JScrollPane scroller = new JScrollPane(textarea);
JScrollPane scroller = new JScrollPane(table);
contentPanel.add(scroller);
scroller.setSize(650,300);
scroller.setLocation(20, 150);
textarea.setLineWrap(true);
model.addColumn("Payment Number");
model.addColumn("Current Interest");
model.addColumn("Principal Paid");
model.addColumn("New Balance");
//Buttons
exitButton = new JButton("Exit");
exitButton.setLocation(450, 30);
exitButton.setSize(100, 25);
contentPanel.add(exitButton);
clearButton = new JButton("Clear");
clearButton.setLocation(450, 55);
clearButton.setSize(100, 25);
contentPanel.add(clearButton);
calculateButton = new JButton("Calculate");
calculateButton.setLocation(450, 85);
calculateButton.setSize(100, 25);
contentPanel.add(calculateButton);
//setup up buttons
calculateButton.addActionListener(this);
clearButton.addActionListener(this);
exitButton.addActionListener(this);
return contentPanel;
}
//Define actions performed for buttons
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
if (e.getSource() == loansList) {
switch (loansList.getSelectedIndex()) {
case 0:
i = 0;
break;
case 1:
i = 1;
break;
case 2:
i = 2;
break;
}
}
if (arg == "Calculate")
{
txtPayment.setText("");
principal = txtMortgage.getText();
try {
intPrincipal = Double.parseDouble(principal);
if (intPrincipal <= 0) throw new NumberFormatException();
}
catch(NumberFormatException n){
txtPayment.setText("Please Enter a Postive Numeric Number");
done = 1;
}
if (done == 1)
done = 0;
else {
interestRate = loanInterest[i];
termYears = loanTerm[i];
monthlyInterest = interestRate/(12*100); //calculates monthly interest
termMonths = termYears*12; //calculates term length in months
calcPayment = monthlyInterest*intPrincipal/(1-Math.pow((1+monthlyInterest), -termMonths)); //calculates monthly payment
txtPayment.setText(" " + df.format(calcPayment));
for (m=0; m<=totalMonths; m++) {
totalMonths = loanTerm[i]*12;
currentInterest = intPrincipal * monthlyInterest;
principalPaid = calcPayment - currentInterest;
newBalance = intPrincipal - principalPaid;
intPrincipal = newBalance;
/* printAndAppend(
(m+1) + " " +
df.format(currentInterest) + " " +
df.format(principalPaid) + " " +
df.format(newBalance) + "\n");
//textarea.setText(df.format(currentInterest));
if(intPrincipal <= 1){ break;}*/
// Create a couple of columns
model.addRow(new Object[]{m+1, df.format(currentInterest), df.format(principalPaid), df.format(newBalance)});
if(intPrincipal <= 1){ break;}
}
}
}
else if (e.getSource() == clearButton)
{
txtMortgage.setText(""); //clear Mortgage textfield
txtPayment.setText(""); //clear Payment textfield
txtMortgage.requestFocusInWindow(); //move cursor back to Mortgage textfield
loansList.setSelectedIndex(0);
}
else if (e.getSource() == exitButton)
System.exit(0);
}
public void printAndAppend(String text) {
textarea.append(text);
}
public static void main(String[] args)
{
new MortgageCalculator().setVisible(true);
}
}
To clear all you need to do is set the row count of the model to 0 -- that's it:
else if (e.getSource() == clearButton) {
txtMortgage.setText("");
txtPayment.setText("");
txtMortgage.requestFocusInWindow();
loansList.setSelectedIndex(0);
model.setRowCount(0); //!! added
}
Also, this is not good:
if (arg == "Calculate") {
As you shouldn't use == to compare Strings. If you want to compare Strings, use the equals method:
if (arg.equals("Calculate")) {
or the equalsIgnoreCase method:
if (arg.equalsIgnoreCase("Calculate")) {
The reason this is important is because == checks to see if one String object is the same as another String object, and you really don't care about this. Instead you want to know if one String holds the same chars as another, and that's what equals tests for.
Also, I'd set the model's row count to 0 at the beginning of your calculate method, and this way you can recalculate things without having to clear.