Question: How do I go about setting the ActionListener of my Shuffle button to do just what the button declares it does, and that is, to shuffle the 3 cards (out of 54 in an image folder) displayed on the screen? They appear randomly each time I run the program, and that's fine and all, but I'm needing to add a shuffle button that'll allow those changes to happen without having to restart the program.
Here is what I've got so far..
//Jeffrey Zachary
//Advanced Java: Sept 15 2013
//Display 3 cards, shuffle them when called to do so
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
class DisplayCards extends JFrame implements ActionListener{
private JPanel cards;
private JButton shuffle;
private JLabel c1, c2, c3;
private Container contents;
private ImageIcon[] imIc;
int cardA = 1 + (int)(Math.random() * 54);
int cardB = 1 + (int)(Math.random() * 54);
int cardC = 1 + (int)(Math.random() * 54);
//create variables to store the random number for card
private ImageIcon firstCard = new ImageIcon("card/" + cardA + ".png");
private ImageIcon secondCard = new ImageIcon("card/" + cardB + ".png");
private ImageIcon thirdCard = new ImageIcon("card/" + cardC + ".png");
public DisplayCards(){
super("Display three cards");
contents = getContentPane();
contents.setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creating card labels
c1 = new JLabel(firstCard, JLabel.CENTER);
c2 = new JLabel(secondCard, JLabel.CENTER);
c3 = new JLabel(thirdCard, JLabel.CENTER);
//Creating panel
cards = new JPanel(new BorderLayout());
//Creating button
shuffle = new JButton("Shuffle");
shuffle.addActionListener(this);
//Adding buttons
cards.add(shuffle, BorderLayout.PAGE_END);
//Adding labels
cards.add(c1, BorderLayout.LINE_START);
cards.add(c2, BorderLayout.CENTER);
cards.add(c3, BorderLayout.LINE_END);
contents.add(cards, BorderLayout.CENTER);
setResizable(false);
setSize(255, 177);
setVisible(true);
}
public static void main(String[] args) {
DisplayCards dc = new DisplayCards();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == shuffle){
}
}
}
Can't create a new homework tag (hint hint) :) -No holding hands here-
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == shuffle) {
cardA = 1 + (int)(Math.random() * 54);
while(cardB == cardA){
cardB = 1 + (int)(Math.random() * 54);
}
while (cardC == cardB || cardC == cardB){
cardC = 1 + (int)(Math.random() * 54);
}
firstCard = new ImageIcon("card/" + Integer.toString(cardA) + ".png");
secondCard = new ImageIcon("card/" + Integer.toString(cardB) + ".png");
thirdCard = new ImageIcon("card/" + Integer.toString(cardC) + ".png");
DisplayCards()
}
}
Something like this with loops preventing the cards from matching may be appropriate here, as it is a small number of cards you need to confirm the uniqueness of.
The loops keep creating a random number until it does not match the previous numbers. Once done you re-select the appropriate cards and re-display them.
Try this, it should work. The idea is to link an ActionEvent to the code you want to execute each time the button is hit. Read this for details.
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == shuffle) {
// add code here for shuffling 3 cards
}
}
Related
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.
The question field should contain 36 questions, the answer to these question are on the 36 buttons in the grid.
i am having a problem getting question field to display 36 question starting with what is 0 + 1 when the user clicks the correct button it then shows question 2 shows in the field which is what is 1+1 and so till question 36
so how do i get one question JLabel and swap the text it holds via the JLabel's setText(...) method
here is my code
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS*COLUMNS];
JLabel statusLabel = new JLabel("",JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS,COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for(int x = 0, y = ROWS*COLUMNS; x < y; x++){
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x+1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel,BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset(){
Collections.shuffle(buttonNumbers);
for(int x = 0, y = ROWS*COLUMNS; x < y; x++){
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 1;
statusLabel.setText("what is 0+ 1 " + buttonCounter);
}
public static void main(String[] args) {
new NewClass();
}
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g){
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton)e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
if(clickedNumber == gui.buttonCounter){
gui.buttonCounter++;
buttonClicked.setText("");//optional - clears correct selection
if(gui.buttonCounter > gui.ROWS*gui.COLUMNS) gui.reset();
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
}
else {
gui.reset();
gui.statusLabel.setText("Incorrect button clicked, start again: what is 0+ 1");
}
}
}
Change one line of code in the action listener. Change this:
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
to this:
gui.statusLabel.setText("what is " + gui.buttonCounter + "+ 1");
Now it will ask:
what is 0+ 1
what is 1+ 1
what is 2+ 1
what is 3+ 1
..........................................
what is 1937655087345+ 1
The question field should contain 36 questions, the answer to these question are on the 36 buttons in the grid.
When the user selects the clicks the correct button answer the button is taken off the grid, the aim is to clear the grid so the grid is empty.
if the user clicks an incorrect button the game restarts.
i am having a problem with adding the question label.
the question field should display 36 question starting with what is 0 + 1 when the user clicks the correct button it then shows
question 2 shows in the field which is what is 1+1 and so till question 36
i have tried to get this by Changing this line of code
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
to this:
gui.statusLabel.setText("what is " + gui.buttonCounter + "+ 1");
but the games doesnt work properly although the correct answer is selected the code keeps saying doing the "else" in this code ie. Incorrect button clicked, start again: what is 0+ 1
if(clickedNumber == gui.buttonCounter){
gui.buttonCounter++;
buttonClicked.setText("");//optional - clears correct selection
if(gui.buttonCounter > gui.ROWS*gui.COLUMNS) gui.reset();
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
} else {
gui.reset();
gui.statusLabel.setText("Incorrect button clicked, start again: what is 0+ 1");
}
}
}
how do i fix this? so when i click the correct answer button it moves to the next question and does not display Incorrect button clicked, start again: what is 0+ 1.
full code
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS * COLUMNS];
JLabel statusLabel = new JLabel("", JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS, COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x + 1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset() {
Collections.shuffle(buttonNumbers);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 1;
statusLabel.setText("Please click button " + buttonCounter);
}
public static void main(String[] args) {
new NewClass();
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g) {
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton) e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
if (clickedNumber == gui.buttonCounter) {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS)
gui.reset();
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter);
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
}
}
}
So, taking the code from your previous question and adding
System.out.println("ClickedNumber = " + clickedNumber);
System.out.println("gui.buttonCounter = " + gui.buttonCounter);
Into the actionPerformed method it asks...
"What is 0+1 1" (which should be "What is 0+1"). I click "1", which outputs...
ClickedNumber = 1
gui.buttonCounter = 1
So looking at the if statement;
if (clickedNumber == gui.buttonCounter) {
This is true...
Then it asks...
"What is 2+1". I click "3", which outputs...
ClickedNumber = 3
gui.buttonCounter = 2
So looking at the if statement;
if (clickedNumber == gui.buttonCounter) {
Which is false.
There is a logic error in your code. Basically, it's coming down to you not actually knowing what the question is...
Runnable example
Basically what this does is asks...
"What is " + buttonCounter + "+1"?
In the if condition, we assume the buttonCounter is 0 indexed, meaning we need to increase the comparison by 1
if (clickedNumber == (gui.buttonCounter + 1)) {
Or you could reduce the clickedNumeber by 1
if ((clickedNumber - 1) == gui.buttonCounter) {
Remember, you question is always asks "What's the next number", not what's the current number...
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS * COLUMNS];
JLabel statusLabel = new JLabel("", JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS, COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x + 1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset() {
Collections.shuffle(buttonNumbers);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 0;
statusLabel.setText("Please click button " + buttonCounter + "+1");
}
public static void main(String[] args) {
new NewClass();
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g) {
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton) e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
System.out.println("ClickedNumber = " + clickedNumber);
System.out.println("gui.buttonCounter = " + gui.buttonCounter);
if (clickedNumber == (gui.buttonCounter + 1)) {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS) {
gui.reset();
}
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter + "+1");
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
}
}
}
Updated with winner condition
if (clickedNumber == (gui.buttonCounter + 1)) {
if (gui.buttonCounter == (gui.ROWS * gui.COLUMNS) - 1) {
JOptionPane.showMessageDialog(null, "You Win", "Winner", JOptionPane.INFORMATION_MESSAGE);
} else {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS) {
gui.reset();
}
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter + "+1");
}
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
Ok, I'm kinda new to java. I'm making a program that solves for one step equations. I'm having some difficulties running it though. Here is the code for my main file, Main.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
Solve solve = new Solve();
JButton add = new JButton("Add");
JButton sub = new JButton("Subtract");
JButton mult = new JButton("Multiply");
JButton div = new JButton("Divide");
JButton solv = new JButton("Solve!");
JTextArea one = new JTextArea();
JLabel two = new JLabel(" = ");
JLabel three = new JLabel("X");
JLabel four = new JLabel();
JTextArea five = new JTextArea();
JLabel solved = new JLabel();
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
public double funct;
public Main() {
super("Solving a one step equation!");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout layout = new GridLayout();
setLayout(layout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(layout1);
row1.add(add);
row1.add(sub);
row1.add(mult);
row1.add(div);
row1.add(solv);
add(row1);
add.addActionListener(this);
sub.addActionListener(this);
mult.addActionListener(this);
div.addActionListener(this);
solv.addActionListener(this);
GridLayout layout2 = new GridLayout(1, 1, 1, 1);
row2.setLayout(layout2);
row2.add(one, BorderLayout.CENTER);
row2.add(two, BorderLayout.CENTER);
row2.add(three, BorderLayout.CENTER);
row2.add(four, BorderLayout.CENTER);
row2.add(five);
add(row2, BorderLayout.CENTER);
GridLayout layout3 = new GridLayout(5, 5, 5, 5);
row3.setLayout(layout3);
row3.add(solved);
add(row3);
}
public static void main(String[] args) {
Main frame = new Main();
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if(source == add)
{
four.setText(" + ");
funct = 1;
}
else if(source == sub)
{
four.setText(" - ");
funct = 2;
}
else if(source == mult)
{
four.setText(" * ");
funct = 3;
}
else if(source == div)
{
four.setText(" / ");
funct = 4;
}
if(source == solv)
{
if(funct == 1)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Add(Ones, Twos));
}
else if(funct == 2)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Sub(Ones, Twos));
}
else if(funct == 3)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Mult(Ones, Twos));
}
else if(funct == 4)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Div(Ones, Twos));
}
}
}
}
Here is the code for my other file, Solve.java
public class Solve {
public double Add(double One, double Two)
{
return One - Two;
}
public double Sub(double One, double Two)
{
return One + Two;
}
public double Mult(double One, double Two)
{
return One / Two;
}
public double Div(double One, double Two)
{
return One * Two;
}
}
Some help would be appreciated. Anyone see what I'm doing wrong?
You get a NumberFormatException once 'Solve' button is clicked. It seems like a copy/paste issue - you are not retrieving the correct numbers. You are trying to convert 'X' string to double. It is best if you give meaningful names to your variables. To fix the exception, try this, replace :
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
with:
double Ones = Double.parseDouble(one.getText());
double Twos = Double.parseDouble(five.getText());
Get familiar with Java Code Conventions, Naming Conventions section in particular.
In addition to #Max's helpful answer, here are a few other suggestions:
Setting the frame's layout to new GridLayout() defaults to a single row and column with no padding. As an alternative, consider new GridLayout(0, 1, 5, 5), which produces any number of rows in one column with 5x5 padding. Then you can focus on the layout of each row:
row1.setLayout(new FlowLayout(FlowLayout.CENTER));
row2.setLayout(new FlowLayout(FlowLayout.CENTER));
row3.setLayout(new GridLayout(1, 1, 5, 5));
Move your setVisible() call to the end of the frame's constructor:
pack();
setLocationRelativeTo(null);
setVisible(true);
Consider getRootPane().setDefaultButton(solv) to make the Solve button the default.
Consider making addition the default:
private JLabel four = new JLabel("+");
private int funct = 1; // add by default
Consider using JTextField for number entry:
private JTextField one = new JTextField(10);
private JTextField five = new JTextField(10);
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.