link logic class into my gui class java - java

hello i was wondering how do i link my logic class to my gui class?
i have wrote a logic class which is the structure then had to give it an interface; so i wrote another class which is the gui class but idk how to make the GUI class grab the variable from the logic class.
P.S: its a number guessing game that the user has to guess a numb btw 1-10.
LOGIC CLASS
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GG {
public static void main(String[] args)
{
//random number
Random rand = new Random();
int answer = rand.nextInt(10) +1;
int guess = 0;
int attempts = 0;
public
//user's guess
Scanner keyboard = new Scanner(System.in);
GuessingGameGui gui = new GuessingGameGui();
gui.setVisible(true);
while(answer != guess)
{
try
{
System.out.print("Guess a number between 1 and 10: ");
attempts++;
guess = keyboard.nextInt();
if (guess < 1 || guess > 10)
//throw new BadGuessException()
throw new BadGuessException("invalid entry (" + attempts + " attempts so far)");
}
catch (BadGuessException e)
{
System.out.println(e.getMessage());
}
catch (InputMismatchException e)
{
System.out.println("Please enter integers only, and try again");
keyboard.next(); //to get rid of infinite loop issue
}
}
System.out.println("YOU GOT IT (" + attempts + "attempts )");
}
}
GUI CLASS
public class GuessingGameGui extends JFrame {
public GuessingGameGui() {
final int WINDOW_WIDTH = 650; // Window width in pixels
final int WINDOW_HEIGHT = 250; // Window height in pixels
setTitle("Guessing Game");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel north = new JPanel();
JLabel lab1 = new JLabel("Guess a number between 1 and 10?");
setLayout(new FlowLayout());
north.add(lab1);
add( north );
JPanel center = new JPanel();
final JTextField titleText = new JTextField();
titleText.setPreferredSize( new Dimension( 200, 24 ) );
setLayout(new FlowLayout());
JButton button = new JButton("Guess");
Action action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
String typed = titleText.getText();
int guess = Integer.parseInt(typed);
}
};
titleText.addActionListener( action );
button.addActionListener( action );
center.add(titleText);
center.add(button);
add( center );
JPanel south = new JPanel();
JLabel lab2 = new JLabel("YOU GOT IT " + attempts);
south.add(lab2);
add( south );
}
}

A common way is to add the Logic object to the GUI, for example through the constructor. Then whenever something is happening on the GUI you need to call the correct methods on the Logic object and update the display if needed.

Related

Generate JFrames in a loop, naming issue

Beginner Java programmer here. I'm trying to create a card game to learn more about Java. I have an array of names I pulled out a database. For each String in the array I want to create a JPanel and inside JLabels where I will set the name, power, health, etc.
The problem is when I create these in a loop they all have the same name and overwrite each other. Since I read Java doesn't have dynamic Variable names, how do I solve this?
public void loadDatabaseCardElements(ArrayList cards) {
ArrayList<String> buildCards = cards;
int i;
for(i = 0; i != buildCards.size();) {
String var = buildCards.get(0);
//create the Panel etc
JPanel mainHolder = new JPanel();
mainHolder.setLayout(new BoxLayout(mainHolder, BoxLayout.PAGE_AXIS));
JLabel name = new JLabel("Name: " + var);
JLabel powerLabel = new JLabel("Power: ");
JLabel healthLabel = new JLabel("Health: ");
JLabel armorLabel = new JLabel("Armor: ");
JLabel type1Label = new JLabel("Type1");
JLabel type2Label = new JLabel("Type2: ");
JLabel ability1Label = new JLabel("Ability1: ");
JLabel ability2Label = new JLabel("Ability2: ");
JLabel ability3Label = new JLabel("Ability3: ");
JButton card1 = new JButton("Add to deck");
mainHolder.add(name);
mainHolder.add(powerLabel);
mainHolder.add(healthLabel);
mainHolder.add(armorLabel);
mainHolder.add(type1Label);
mainHolder.add(type2Label);
mainHolder.add(ability1Label);
mainHolder.add(ability2Label);
mainHolder.add(ability3Label);
mainHolder.add(card1);
mainHolder.setBorder(BorderFactory.createLineBorder(Color.black));
mainHolder.setPreferredSize( new Dimension( 130, 200 ) );
frame1.add(mainHolder, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(frame1);
card1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
preDeck.add(var); //add to another array when clicked
}
});
if (buildCards.size() != 0) {
buildCards.remove(0);
} else {
}
}
}
The reason for overwriting all the panels with same name is due to this part of your code:
int i;
for(i = 0; i != buildCards.size();) {
String var = buildCards.get(0);
You are assigning the first element of your list to each JLabel. This could help you achieve what you need:
for(int i = 0; i < buildCards.size(); i++){
String var = buildCards.get(i);
// Followed by your code
}
set a growable layout for a standard jpanel in the frame and then add a new jpanel to the standard jpanel every time. this should solve the naming problem. if u need access to each panel, you can store them in an array

Basic GUI java program in Eclipse keeps crashing

I am trying to make a game and in said game, there are 21 sticks and each person takes turns taking 1-4 sticks until there are no sticks left, if you cant take anymore sticks you lose. I have successfully made this program in eclipse but now I want to add GUI to it so I have to change the code. This code isn't complete but it crashes whenever I press the Go button which is my actionListener. I would type in a number to the text field, press go and it will just crash. How can I fix this?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sticks extends JFrame {
JButton Go;
JTextField tf1, tf2;
static JTextField sttf;
JLabel startTake;
static JLabel errorTake;
JLabel uTake;
JLabel compTake;
public Sticks() {
setLayout(new GridLayout(5, 2, 5, 5));
startTake = new JLabel("How many sticks do you want to take? (1-4)");
add(startTake);
sttf = new JTextField();
add(sttf);
errorTake = new JLabel("Hello");
add(errorTake);
Go = new JButton("Go");
add(Go);
uTake = new JLabel("");
add(uTake);
compTake = new JLabel("");
add(compTake);
// tf1 = new JTextField();
// add(tf1);
// TakeP = new JLabel("One stick taken");
// add(TakeP);
event e = new event();
Go.addActionListener(e);
}
public static class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
int numSticks = 21;
int numToTake = 0;
int randomNum = 0;
while (numSticks > 0) {
try {
int num = (int) (Double.parseDouble(sttf.getText()));
int NumSticks = numSticks - num;
errorTake.setText("There are: " + numSticks + " left");
Robot Rob = new Robot();
numToTake = (int)Math.random() * 4 + 1;
errorTake.setText("There are: " + numSticks + " left");
}
catch (Exception ex) {
ex.printStackTrace();;errorTake.setText("There is a problem");
}
}
}
}
public static void main(String[] args) {
Sticks gui = new Sticks();
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 200);
gui.setTitle("Nice Game");
}
}
Everytime you click the "Go" button, your actionPerformed fires, and it doesn't wait for user input at all. This is your problem line.
public static class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
//...
int num = (int) (Double.parseDouble(sttf.getText()));
//...
}
}
sttf.getText() always returns "" because sttf is empty, the program doesn't wait for user input unlike Scanner(System.in).
Makes sense that you don't get any Exceptions because it just runs and finishes the game without giving the user enough time to input anything. Are you sure the console doesn't print "Numbers only!", though? Because I've never tried to parse an empty String before.
Okay I've been reading this all wrong, sorry.
Your actionListener generates a new game everytime you click it, because you set your numSticks to 21 at each click. Looking forward, I don't think that's a good idea unless you want to take the same amount of sticks the whole way until the game ends. Same thing stands. If you input a value in sttf, the program won't wait for you to change it because it'd keep using that value until your while loop ends.

GUI hangman game- how can I get these different parts to work together?

I have (almost) working pieces of the game, but they don't work together. I am a complete beginner so I don't know how to work out where the problem is.
I have 3 classes:
GameControls has the main functionality of the game in it.
Hangman sets up a JFrame, calls the drawHangman method and contains the main method
drawHangman has the instructions for drawing the hangman graphic
I suspect this might not be the best way to do this so if the classes make no sense please let me know (and tell me why!).
Problem
GameControls runs fine on its own. The user can select letters to guess, the display works, and the livesRemaining count goes down if the guess is wrong.BUTif I run from the hangman main method, the windows appear and the controls don't work anymore.
Even though the livesRemaining count decreases, I don't know how to make the drawHangman part use that variable and implement the switch statement to draw the hangman.
My ideas
It seems to me that the way the classes/methods are written/designed might be causing issues (but I don't know how to diagnose and fix this. I have tried!)
I thought that the reason for problem 1 could be that when both windows open the program doesn't know where actions are coming from anymore and/or I need to add more ActionListener stuff.
As I'm so new to programming it is taking me ages to look and this and try out different things, I would really like some pointers. My code is below.
Hangman class
public class Hangman extends JFrame
{
public Hangman()
{
super("You have nine lives...");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawHangman draw = new drawHangman();
add(draw);
setVisible(true);
}
public static void main(String[] args)
{
GameControls play = new GameControls();
Hangman game = new Hangman();
}
}
}
GameControls class
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class GameControls extends JFrame implements ActionListener
{
String secretWord = "elephant"; //I'm assuming I will call a method that generates the secretWord
String clueGiven = "animal";
int letterN = 0;
int secretWordLength = secretWord.length();
int livesRemaining = 10;
boolean[] alreadyGuessed = new boolean[26];
JLabel secretWordLabel = new JLabel("Word to guess: ", SwingConstants.RIGHT);
JTextField displaySecretWord = new JTextField(secretWordLength);
JLabel clueLabel = new JLabel("Clue: ", SwingConstants.RIGHT);
JTextField clue = new JTextField(clueGiven, 15);
JLabel guessLabel = new JLabel("Choose a letter: ", SwingConstants.RIGHT);
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
JComboBox selectGuess = new JComboBox(letters);
JButton submit = new JButton("Submit");
JTextField displayGuessedLetters = new JTextField(15);
public GameControls()
{
super("Hangman Game");
setSize(340,170);
setBounds(600,0,340,170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
selectGuess.addActionListener(this);
submit.addActionListener(this);
displaySecretWord.setEditable(false);
clue.setEditable(false);
displayGuessedLetters.setEditable(false);
//show _ for all the letters of the secretWord
for (letterN=0; letterN < secretWordLength; letterN++)
{
String displayedSoFar = displaySecretWord.getText();
displaySecretWord.setText(displayedSoFar + " " + "_");
}
JPanel pane = new JPanel();
GridLayout display = new GridLayout(4,2);
pane.setLayout(display);
pane.add(secretWordLabel);
pane.add(displaySecretWord);
pane.add(clueLabel);
pane.add(clue);
pane.add(guessLabel);
pane.add(selectGuess);
pane.add(displayGuessedLetters);
pane.add(submit);
add(pane);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
/*this works just fine when I run just this part of the program
**but if I run it from the hangman main method it doesn't work.
**I think it might be because then it has an extra window
**so it doesn't know where the action is coming from for these bits here
*/
Object source = event.getSource();
boolean guessInWord;
String prevGuesses = displayGuessedLetters.getText();
char hideLetter = '_';
int guessInt = selectGuess.getSelectedIndex();
String guessChar = (String)selectGuess.getItemAt(guessInt);
if (source == submit)
{
//store word as alreadyGuessed
alreadyGuessed[guessInt]=true;
//check if it's in the word
guessInWord = (secretWord.indexOf(guessChar)) != -1;
boolean wordComplete = false;
if (guessInWord == true)
{
//print out the secretWord with the guessed letters showing
displaySecretWord.setText(" ");
for (letterN=0; letterN < secretWordLength; letterN++)
{
String displayedSoFar = displaySecretWord.getText();
char letterToCheck = secretWord.charAt(letterN);
int letterToCheckIndex = (int)(letterToCheck)- 97;
if (alreadyGuessed[letterToCheckIndex]==true)
{
displaySecretWord.getText();
displaySecretWord.setText(displayedSoFar + " " + letterToCheck);
}
else if (alreadyGuessed[letterToCheckIndex]==false)
{
displaySecretWord.getText();
displaySecretWord.setText(displayedSoFar + " " + hideLetter);
}
}
//check if the word is complete or not
String displayedSoFar = displaySecretWord.getText();
wordComplete = displayedSoFar.indexOf("_")== -1;
if (wordComplete == true)
{
//this bit opens but I haven't finished it yet
youWinPopup win = new youWinPopup();
}
}
else if (guessInWord == false)
{
//I can't figure out how to link this to my hangman drawing part!
livesRemaining --;
System.out.println(livesRemaining);
displayGuessedLetters.setText(prevGuesses + " " + guessChar);
}
}
}
private void setLookAndFeel()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception exc)
{
System.out.println("Couldn't use the system " + "look and feel: " + exc);
}
}
/*public static void main (String[] args)
{
GameControls play = new GameControls(); //runs fine from here, without the hangman part
}*/
}
drawHangman class
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class drawHangman extends JPanel
{
/**
*
*/
private static final long serialVersionUID = -3924721752542320241L;
public void paintComponent (Graphics comp)
{
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setColor(Color.white);
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Rectangle2D.Float background = new Rectangle2D.Float(0F,0F,400,600/*(float)getSize().width,(float)getSize().height*/);
comp2D.fill(background);
//setting for colour etc
comp2D.setColor(Color.black);
BasicStroke pen = new BasicStroke(2.0f,BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
comp2D.setStroke(pen);
int livesRemaining = 10;
switch (livesRemaining)
{
case '9':
Line2D.Float gallowsBase = new Line2D.Float(50F,500F,500F,500F);
comp2D.draw(gallowsBase);
break;
case '8':
Line2D.Float gallowsVertical = new Line2D.Float(150F,500F,150F,100F);
comp2D.draw(gallowsVertical);
break;
case '7':
Line2D.Float gallowsTop = new Line2D.Float(150F,100F,400F,100F);
comp2D.draw(gallowsTop);
break;
case '6':
Line2D.Float rope = new Line2D.Float(400F,100F,400F,150F);
comp2D.draw(rope);
break;
case '5':
Ellipse2D.Float head = new Ellipse2D.Float(362F,150F,76F,76F);
comp2D.draw(head);
break;
case '4':
Line2D.Float body = new Line2D.Float(400F,226F,400F,325F);
comp2D.draw(body);
break;
case '3':
Line2D.Float arm1 = new Line2D.Float(400F,226F,300F,275F);
comp2D.draw(arm1);
break;
case '2':
Line2D.Float arm2 = new Line2D.Float(400F,226F,500F,275F);
comp2D.draw(arm2);
break;
case '1':
Line2D.Float leg1 = new Line2D.Float(400F,325F,300F,400F);
comp2D.draw(leg1);
break;
case '0':
Line2D.Float leg2 = new Line2D.Float(400F,325F,500F,400F);
comp2D.draw(leg2);
/*youLosePopup lose = new youLosePopup();*/
}
}
/*public static void main (String[] args)
{
drawHangman draw = new drawHangman();
}*/
}
livesRemaining is an integer.
When you put it in a switch statement, your cases should be integers not characters.
case 6:
instead of
case '6':
Good luck.

show warning if users enter letter instead number in java applet

I am writing an tip calculator app in java applet with GUI, my question is how I make sure the error message will pop up if users enter letter instead of number
it is my first time asking question, please be easy on me! Thanks!!!
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Typing in the text field and hitting return adds text to text area.
// Clicking on button erases the text area.
public class TextApplet extends Controller implements ActionListener
{
private static final int ROWS = 1; // rows in TextArea
private static final int COLS = 10; // cols in text field & area
private String amount;
private float number;
private JTextField inField, output; // Input field
private JButton clear, calc;
// button to clear output
public void begin()
{
Container contentPane = getContentPane();
JPanel topPanel = new JPanel(); // prepare text field & label
JLabel inLabel = new JLabel("Bill Cost: ");
inField = new JTextField(COLS);
inField.addActionListener(this);
JLabel topTitle = new JLabel("Tip Calculator", JLabel.CENTER);
JPanel combinePanel = new JPanel();
combinePanel.add ( inLabel );
combinePanel.add ( inField );
JPanel combinePanel1 = new JPanel();
combinePanel1.add ( topTitle );
topPanel.add ( combinePanel1 );
topPanel.add ( combinePanel );
topPanel.setLayout ( new GridLayout ( 3,1) );
contentPane.add(topPanel,BorderLayout.NORTH);
JPanel centerPanel = new JPanel(); // prepare text area & label
JLabel outLabel = new JLabel("Bill + Tip:");
output = new JTextField(COLS);
output.setEditable(false); // Prevent user from wrting in output
centerPanel.add(outLabel);
centerPanel.add(output);
contentPane.add(centerPanel,BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
// create button
clear = new JButton(" Clear ");
calc = new JButton("Calculate");
calc.addActionListener(this);
clear.addActionListener(this);
bottomPanel.add(calc);
bottomPanel.add(clear);
contentPane.add(bottomPanel,BorderLayout.SOUTH);
validate();
}
// add text to area if user hits return, else erase text area
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == calc )
{
amount = inField.getText();
number = ( Float.parseFloat( amount ) );
number = (15*number/100);
output.setText ( Float.toString ( number ) + '$' );
}
else if (evt.getSource() == clear )
{
output.setText("$");
inField.setText("");
}
}
}
There are any number of ways you might achieve this, you could use
An InputVerifier
A JFormattedTextField
A JSpinner
Or a DocumentFilter and examples
Take a look at javax.swing.InputVerifier. That can be easily attached to a JTextField
JTextField inputField = new JTextField();
inputField.setInputVerifier(new NumericInputVerifier());
private class NumericInputVerifier extends InputVerifier
{
#Override
public boolean verify(JComponent input)
{
if (((JTextField) input).getText().matches("[0-9]+"))
{
return true;
}
else
{
JOptionPane.showMessageDialog(input, "Only numbers are allowed", "Warning", JOptionPane.WARNING_MESSAGE);
return false;
}
}
}
A complete example can be found here.
Edit Added an example of how to use InputVerifier to limit to numeric input. You'll want to double check the regex, but the basic idea is there...
Use a JFormattedTextField or a DocumentFilter. Then the user won't even be able to enter a non-numeric digit. See:
How to Use Formatted Text Fields
Implementing a Document Filter
For the document filter you will need to check each chraacter as it is entered to make sure it is a digit.
It is always better to do simple edits like that as the user types, rather than wait until you click on a button to do processing.
Hello Friend I will give a suggestion
please add validation when call actionPerformed method
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == calc )
{
if(validate()){
amount = inField.getText();
number = ( Float.parseFloat( amount ) );
number = (15*number/100);
output.setText ( Float.toString ( number ) + '$' );
}
else{
// show message for inter valid number or any other
}
}
else if (evt.getSource() == clear )
{
output.setText("$");
inField.setText("");
}
}
boolean validate(){
try{
amount = inField.getText();
number = ( Float.parseFloat( amount ) );
return true;
}
catch(Exception e){
return false;
}
}
If you try to call Float.parseFloat on a String that cannot be converted to a float, it will throw a NumberFormatException. You need to catch this exception.
try {
number = ( Float.parseFloat( amount ) );
number = (15*number/100);
output.setText ( Float.toString ( number ) + '$' );
} catch(NumberFormatException e) {
//code to show error message here
}
Well considering, you'd have to turn the string into an integer to do the math, you could do this:
try {
int number = Ineger.parseInt(inField.getText());
} catch (NumberFormatException e) {
//SHOW WARNING
}
if (Label1.getText().matches("[0-9]+"))
// does Label1 containts numbers.
{
// do math
}
else
{
// warning
Lavbel1.setText("");
}

java Clear Table on button click

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.

Categories