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.
Related
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
With this code, i want to develop a program that enables the user to enter 5 int values into a single textfield. These values will be stored in an array and upon pressing the button, a bar graph will be drawn to represent the entered values. Class BtnHandler handles the button click event and class gegHandler handles the textfield enter event. I can't get the user input to be collected in the array. Here is my code.
package voorbeeld0805;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Vb0805 extends JFrame {
public static void main( String args[] ) {
JFrame frame = new Vb0805();
frame.setSize( 300, 300 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Voorbeeld 0805" );
frame.setContentPane( new Tekenpaneel() );
frame.setVisible( true );
}
}
class Tekenpaneel extends JPanel {
private Staafdiagram staafdiagram;
private JButton knopTeken;
private JTextField gegevensVak;
private JLabel lblNo;
private int[] lengtes = new int [5];
public Tekenpaneel() {
setBackground( Color.ORANGE );
knopTeken = new JButton("Teken");
knopTeken.addActionListener(new BtnHandler());
gegevensVak = new JTextField(5);
gegevensVak.addActionListener(new gegHandler());
lblNo = new JLabel("Enter Value");
add(knopTeken);
add (gegevensVak);
add (lblNo);
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
if (staafdiagram != null)
{
staafdiagram.teken( g, 50, 250 );
}
this.requestFocusInWindow();
}
class BtnHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//To test using the first constructor. Works perfectly
/*int [] lengtes = { 144, 98, 117, 130, 172, 173 };
staafdiagram = new Staafdiagram( lengtes, 30 );*/
repaint();
}
}
class gegHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//Here user input should be collected, placed in an array and
//saved in staafdiagram.setLengtes();
for (int i = 0; i < lengtes.length; i++){
lblNo.setText("Next Value Is " + i++);
lengtes[i] = Integer.parseInt( gegevensVak.getText());
gegevensVak.setText("");//clear textfield after entering a value
}
}
}
}
class Staafdiagram {
private int[] lengtes;
private int witruimte;//this generates the spaces between the bars
//First contructor with 2 arguments array en space
public Staafdiagram( int[] lengtes, int witruimte ) {
this.lengtes = lengtes;
this.witruimte = witruimte;
}
//Second constructor with only 1 argument space
public Staafdiagram(int witruimte ) {
this.witruimte = witruimte;
}
//With this, i want the user input to be collected in an array
public void setLengtes(int[] lengtes) {
this.lengtes = lengtes;
}
//To calculate the bar with the highest value
public int bepaalMax(){
int maximum = lengtes [0];
for (int i = 1; i < lengtes.length; i++){
if (lengtes[i] > maximum)
{
maximum = lengtes[i];
}
}
return maximum;
}
//To calculate the bar with the lowest value
public int bepaalMin(){
int minimum = lengtes [0];
for (int i = 1; i < lengtes.length; i++){
if (lengtes[i] < minimum)
{
minimum = lengtes[i];
}
}
return minimum;
}
public void teken( Graphics g, int x, int y ) {
int startX = x;
// Draw the bars
for( int lengte : lengtes ) {
if (lengte == bepaalMax())
g.setColor(Color.red);
else if (lengte == bepaalMin())
g.setColor(Color.green);
else
g.setColor(Color.black);
g.fillRect( x, y - 20 - lengte, 20, lengte );
x += witruimte;
}
// Display the values under the bars
x = startX;
for( int lengte : lengtes ) {
g.drawString( String.format( "%d", lengte ), x, y );
x += witruimte;
}
}
}
If you add an ActionListener on a JTextField, the actionPerformed() method is called when you "action" this field : here is the enter key pressed.
If you want associate the button to your action, you should rather enrich the ActionListener you defined on the JButton to also get the values entered by the user. The idea is chaining the both as both operations should performed one after the other one :
These values will be stored in an array and upon pressing the button,
a bar graph will be drawn to represent the entered values.
class BtnHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
// collection information from textfield
for (int i = 0; i < lengtes.length; i++){
lblNo.setText("Next Value Is " + i++);
lengtes[i] = Integer.parseInt( gegevensVak.getText());
gegevensVak.setText("");//clear textfield after entering a value
}
// rendering
staafdiagram = new Staafdiagram( lengtes, 30 );*/
repaint();
}
}
Get the input from the text field as text
split to string array
Convert to int
MOdify your code as follows.
class BtnHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//To test using the first constructor. Works perfectly
/*int [] lengtes = { 144, 98, 117, 130, 172, 173 };
staafdiagram = new Staafdiagram( lengtes, 30 );*/
String textInt=gegevensVak .getText(); //gegevensVak is the name of the textfield you mentioned
String[] strArray = textInt.split();
//now convert the string to int and add to a new array
repaint();
}
}
Hello everyone my first question on stack overflow
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
public class TI extends JFrame implements ActionListener
{
static int count=0;
String ct;
JTextField word;
JTextArea tohide;
public static void main(String arg[])
{
TI ti=new TI();
}
public TI()
{
JPanel j=new JPanel();
JLabel def=new JLabel("Enter the text to be encrypted");
word=new JTextField("",20);
tohide=new JTextArea("",5,20);
JButton jb=new JButton("COUNT");
tohide.setBorder(BorderFactory.createLoweredBevelBorder());
j.add(def);
j.add(tohide);
j.add(word);
j.add(jb);
add(j);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
jb.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String txt=tohide.getText();
StringTokenizer stk=new StringTokenizer(txt," ");
while(stk.hasMoreTokens())
{
String token=stk.nextToken();
count++;
}
ct=Integer.toString(count);;
word.setText(ct);
}
}
I want to count the number of words that are being typed in the textarea.There is a logical error.As I keep clicking the count button the word count increases.
You never reset the count to 0 before recalculating the number of words. There doesn't seem to be a need for count to be a class variable. Making that change would make this kind of mistake impossible.
Use javax.swing.text.Utilities which has
public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)
Separating by spaces is not enough. The separator could be also tab, \n etc. chars
public void actionPerformed(ActionEvent ae) {
word.setText(String.valueOf(tohide.getText().split("\\s").length));
}
I am using the following code to do the task. The idea behind it is that each pair of words is separated by a space. hence using space to split seems straight forward. if words contain carriage return, then, replacing the carriage return with empty string has to be done before counting. I hope that it helps
public int WordCount(String Words){
//Initiate Result
String s = Words+" "; //Add space after the received string
String result ="";
int i = 0;
int count = s.length();
try {
for (i = 0; i <= count - 1; i++) {
if (count - i > 1) {
String tempString = s.substring(0, s.indexOf(" "));
if (s.contains(" ") && (!s.isEmpty())) {
s = s.substring(s.indexOf(" ") + 1, s.length());
//get substring between " " and lenght ;
} else {
if(!s.isEmpty()) {
//output nothing
}
}
} else {
//output nothing;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return i;
}
I've just started learning Java, so I apologize if this question is somewhat basic, and I'm sure my code is not as clean as it could be. I've been trying to write a small quiz program that will input a list of German verbs from a txt file (verblist.txt). Each line of the text file contains five strings: the German verb (verbger), the English translation (verbeng), the praeteritum and perfekt conjugations conjugations (verbprae and verbperf) and whether it uses haben or sein as the auxiliary verb (H or S, stored as verbhaben). The verb set is chosen by generating a random number and selecting the "row" of the two dimensional array. The GUI then displays the first two variables, and the user has to input the last three. If the last three match the values in the txt file, the user gets it correct and moves on to another verb.
I'm at the point where the code is working the way I want it to - for one verb. The way I've been organizing it is in two classes. One, VerbTable, imports the text file as a two dimensional array, and the other, RunVerb, generates the GUI and uses an ActionListener to compare the user input to the array. What I can't figure out now is how, after the user gets one verb set correct, I can then loop through the entire set of verbs.
I was thinking of creating a for loop that loops through the number of rows in the text file (saved in the code as height), generating a new random number each time to select a different verb set (or "row" in the two dimensional array.) Essentially, I'd like to get a loop to run through the entire VerbRun class, and pause for the ActionListener, until all of the verb sets have been displayed.
Here is the VerbTable class, which generates the array and random number to select the row:
package looptest;
import java.io.*;
import java.util.*;
public class VerbTable {
public int width;
public int height;
public int randnum;
public String verbger = new String("");
public String verbeng = new String("");
public String verbprae = new String("");
public String verbperf = new String("");
public String verbhaben = new String("");
public VerbTable() {
File file = new File("verblist.txt");
try {
/* For array height and width */
Scanner scanner1 = new Scanner(file).useDelimiter("\n");
int height = 0;
int width = 0;
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
height++;
String[] line3 = line.split("\t");
width = line3.length;
}
System.out.println("Height: " + height);
System.out.println("Width: " + width);
this.width = width;
this.height = height;
/* Array height/width end */
/* random number generator */
int randnum1 = 1 + (int)(Math.random() * (height-1));
this.randnum = randnum1;
/* random number generator end */
Scanner scanner = new Scanner(file).useDelimiter("\n");
String verbtable[][];
verbtable = new String[width][height];
int j = 0;
while (scanner.hasNextLine()){
String verblist2 = scanner.next();
String[] verblist1 = verblist2.split("\t");
System.out.println(verblist2);
verbtable[0][j] = verblist1[0];
verbtable[1][j] = verblist1[1];
verbtable[2][j] = verblist1[2];
verbtable[3][j] = verblist1[3];
verbtable[4][j] = verblist1[4];
j++;
}
this.verbger = verbtable[0][randnum];
this.verbeng = verbtable[1][randnum];
this.verbprae = verbtable[2][randnum];
this.verbperf = verbtable[3][randnum];
this.verbhaben = verbtable[4][randnum];
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
public int getRand(){
return this.randnum;
}
public int getWidth(){
return this.width;
}
public int getHeight(){
return this.height;
}
public String getVerbger(){
return this.verbger;
}
public String getVerbeng(){
return this.verbeng;
}
public String getVerbprae(){
return this.verbprae;
}
public String getVerbperf(){
return this.verbperf;
}
public String getVerbhaben(){
return this.verbhaben;
}
public static void main(String[] args) throws IOException {
}
}
And here is the RunVerb class:
package looptest;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RunVerb extends JFrame {
VerbTable dimensions = new VerbTable();
int width = dimensions.getWidth();
int height = dimensions.getHeight();
int randnum = dimensions.getRand();
String verbgerin = dimensions.getVerbger();
String verbengin = dimensions.getVerbeng();
String verbpraein = dimensions.getVerbprae();
String verbperfin = dimensions.getVerbperf();
String verbhabenin = dimensions.getVerbhaben();
String HabenSeinSelect = new String("");
public JTextField prae = new JTextField("",8);
public JTextField perf = new JTextField("",8);
public JLabel verbger = new JLabel(verbgerin);
public JLabel verbeng = new JLabel(verbengin);
public JRadioButton haben = new JRadioButton("Haben");
public JRadioButton sein = new JRadioButton("Sein");
public RunVerb() {
JButton enter = new JButton("Enter");
enter.addActionListener(new ConvertBtnListener());
prae.addActionListener(new ConvertBtnListener());
perf.addActionListener(new ConvertBtnListener());
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(verbger);
verbger.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));
content.add(verbeng);
verbeng.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 40));
content.add(new JLabel("Praeteritum:"));
content.add(prae);
content.add(new JLabel("Perfekt:"));
content.add(perf);
content.add(haben);
haben.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 10));
haben.setSelected(true);
content.add(sein);
sein.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
ButtonGroup bg = new ButtonGroup();
bg.add(haben);
bg.add(sein);
content.add(enter);
setContentPane(content);
pack();
setTitle("Verben");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class ConvertBtnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String outprae = prae.getText();
int praenum = 0;
if (outprae.equals(verbpraein)){
praenum = 1;
}
String outperf = perf.getText();
int perfnum = 0;
if (outperf.equals(verbperfin)){
perfnum = 1;
}
boolean habenselect = haben.isSelected();
boolean seinselect = sein.isSelected();
if (habenselect == true){
HabenSeinSelect = "H";
}
else {
HabenSeinSelect = "S";
}
int habennum = 0;
if (HabenSeinSelect.equals(verbhabenin)) {
habennum = 1;
}
int numtot = praenum + perfnum + habennum;
if (numtot == 3){
System.out.println("Correct.");
}
else{
System.out.println("Incorrect.");
}
numtot = 0;
}
}
public static void main(String[] args) {
window.setVisible(true);
}
}
So what would be the best way to cycle through the entire verbtable array until all of the rows have been displayed? Should I create a for loop, and if so, where should it go? Should I make a new class that contains the loop and references the VerbRun class? If so, what would be the best way to go about it?
I hope this makes sense! Thank you!
To go through all the verbs exactly in a random order, you may not want to generate random numbers each time, as the random number can repeat. You have to create a random permutation of verbs, one way to do it is Collections.shuffle
see http://download.oracle.com/javase/6/docs/api/java/util/Collections.html
Also You dont have to create a new RunVerb Object, instead create once, and use setters to change the UI, and the functionality of Action Listeners. So pseudo code would be
Collections.shuffle(verbsList);
for(verb : verbsList)
{
setLabel1(verb[0]);
setLabel2(verb[1]);...
}
I would have a method like getNextRandomVerb() in then VerbTable class that generates the next verb to be shown. It will keep track of the verbs that have been shown ( for a given user-session ofcourse ) already and ensure the next one picked is not a repeat. Your RunVerb class seems to more responsible for managing the GUI , so this is not the place to define how to get the next verb to display.
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.