How can I make a calendar using JComboBox? - java

I want to make it adaptive, like if Feb got 29 days in 2000 but it will change into 28 when 2001.
I want to do it while using JComboBox
How can I make action calendar using a combo box?
JComboBox jcb,jcb1,jcb2;
db(){
JFrame jf = new JFrame("register");
jf.setLayout=(new FlowLayout());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String aa1="0"+1+"-"+"0"+2+"-"+2000;
date = LocalDate.parse(aa1,dtf);
Integer day[] = new Integer[date.lengthOfMonth()];
for(int i=0;i<date.lengthOfMonth();i++) {
day[i]=i+1;
}
jcb = new JComboBox<>(day);
Integer month[] = new Integer[12];
for(int i=0;i<12;i++) {
month[i]=i+1;
}
jcb1 = new JComboBox<>(month);
Integer year[] = new Integer[80];
for(int i=0;i<80;i++) {
year[i]=i+1940;
}
jcb2 = new JComboBox<>(year);
jf.add(jcb);
jf.add(jcb1);
jf.add(jcb2);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setBounds(300,300,300,300);
jf.setVisible(true);
}

As #Andrew Thompson mentioned in comments, JComboBoxes for date selection is not a good idea. Take a look at Which one is the best Java datepicker.
However, if you still insist of using comboboxes, in order to achieve what you want, you will have to add an ActionListener to month/year combobox in order to re-fix the model (items) of days combobox.
Take a look at this example:
public class Test extends JFrame implements ActionListener {
private JComboBox<Integer> yearBox;
private JComboBox<Integer> monthBox;
private JComboBox<Integer> dayBox;
public Test() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
yearBox = new JComboBox<>();
for (int i = 1940; i <= LocalDateTime.now().getYear(); i++) {
yearBox.addItem(i);
}
yearBox.addActionListener(this);
monthBox = new JComboBox<>();
for (int i = 1; i <= 12; i++) {
monthBox.addItem(i);
}
monthBox.addActionListener(this);
dayBox = new JComboBox<>();
add(new JLabel("year:"));
add(yearBox);
add(new JLabel("month:"));
add(monthBox);
add(new JLabel("day:"));
add(dayBox);
//Start with current year selected
yearBox.setSelectedIndex(yearBox.getItemCount() - 1);
setSize(400, 400);
setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
int year = (int) yearBox.getSelectedItem();
int month = (int) monthBox.getSelectedItem();
int daysInThisMonth = LocalDate.of(year, month, 1).lengthOfMonth();
int previousSelection = dayBox.getSelectedItem() != null ? (int) dayBox.getSelectedItem() : 1;
dayBox.removeAllItems();
for (int i = 1; i <= daysInThisMonth; i++) {
dayBox.addItem(i);
}
if (previousSelection >= dayBox.getItemCount())
//select last index of month
dayBox.setSelectedIndex(dayBox.getItemCount() - 1);
else
dayBox.setSelectedItem(previousSelection);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().setVisible(true));
}
}

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

add array to JTextField

I am trying to add the contents of two arrays to two TextFields. When you run the program the problem is the current TextFields that I try to display (lines 70 - 83) when the window is redrawn, they only show the last item in their array. Is there any way to add all the items in a stacked list (one ontop of another.)
This is my first class ClassNameSorting
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ClassNameSorting extends JFrame {
JTextField studentNameInputFirst, studentNameInputLast, studentNamesEneteredLast, studentNamesEnteredFirst;
JButton nextName, sort, backToStart;
JLabel firstName, lastName, classList;
String disp = "";
ArrayList<String> studentNameFirst = new ArrayList<String>();
ArrayList<String> studentNameLast = new ArrayList<String>();
ArrayList<String> sortedStudentNameFirst = new ArrayList<String>();
ArrayList<String> savedUnsortedStudentNameLast = new ArrayList<String>();
Container container = getContentPane();
public ClassNameSorting() {
container.setLayout(new FlowLayout());
studentNameInputFirst = new JTextField(15);
studentNameInputLast = new JTextField(15);
nextName = new JButton("Save");
sort = new JButton("Sort");
firstName = new JLabel("First Name: ");
lastName = new JLabel("Last Name: ");
nextName.setPreferredSize(new Dimension(110, 20));
sort.setPreferredSize(new Dimension(110, 20));
container.add(firstName);
container.add(studentNameInputFirst);
container.add(lastName);
container.add(studentNameInputLast);
container.add(nextName);
container.add(sort);
nextName.addActionListener(new nextNameListener());
sort.addActionListener(new sortListener());
setSize(262, 120);
setVisible(true);
}
private class nextNameListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
studentNameFirst.add(studentNameInputFirst.getText());
studentNameLast.add(studentNameInputLast.getText());
studentNameInputLast.setText(null);
studentNameInputFirst.setText(null);
}
}
private class sortListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
savedUnsortedStudentNameLast = new ArrayList<String>(studentNameLast);
Collections.sort(studentNameLast);
int totalSizeOfArray = studentNameLast.size();
for(int i = 0; i < totalSizeOfArray; i++){
boolean containsYorN = false;
String tempElementForContains = studentNameLast.get(i);
String tempElementFromStudentNameLast = savedUnsortedStudentNameLast.get(i);
containsYorN = savedUnsortedStudentNameLast.contains(tempElementForContains);
if(containsYorN == true){
int tempIndexPos = savedUnsortedStudentNameLast.indexOf(tempElementForContains);
String tempIndexElement = studentNameFirst.get(tempIndexPos);
sortedStudentNameFirst.add(i, tempIndexElement);
}
}
studentNamesEneteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
}
studentNamesEneteredLast.setEditable(false);
studentNamesEnteredFirst.setEditable(false);
container.add(studentNamesEneteredLast);
container.add(studentNamesEnteredFirst);
setSize(262, 500);
revalidate();
}
}
}
My second class is: (DrawMainWindow)
import javax.swing.JFrame;
public class DrawMainWindow {
public static void main(String[] args) {
ClassNameSorting drawGui = new ClassNameSorting();
drawGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawGui.setLocationRelativeTo(null);
}
}
The first array is studentNameLast. I am trying to add that to studentNamesEnteredLast text field. The second is sortedStudentNameFirst being added to studentNamesEnteredFirst.
Thanks for the help!
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
The text in the JTextField will only reflect the last item of the List. If you wish to append the entire list, create a String from the List and set the text of the JTextField with that String (you might wish to have them separated by some character - below uses a comma)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < totalSizeOfArray; i++){
sb.append(studentNameLast.get(i)).append(",");//comma delim
}
studentNamesEneteredLast.setText(sb.toString());
Not entirely sure what you are after, but a JList or JTable might be more appropriate to display List information
Was able to switch to a GridLayout and then added each last name and then first name together.
Code:
container.setLayout(new GridLayout(totalSizeOfArray+3,2));
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
studentNamesEnteredFirst.setEditable(false);
studentNamesEnteredLast.setEditable(false);
studentNamesEnteredLast.setText(studentNameLast.get(i));
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
container.add(studentNamesEnteredLast);
container.add(studentNamesEnteredFirst);
}
Example:

NumberFormatException: empty string when clicking the JButton?

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);
}
:)

Insert external class(JTable) into Jpanel

I'm currently working on a project where I have to inser a Jtable(which is a calendar) into a Jpanel.
The problem is that i cant find a way to make it work in the panel(it doesn't even appear).
In part is because I dont have an object to fill the table and that's where I need help because I cant find a way to make it work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class Calendar{
int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);;
JLabel l = new JLabel("", JLabel.CENTER);
String day = "";
JTable d;
JButton[] button = new JButton[49];
public Calendar() {
String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
d = new JTable(header, 0);
DefaultTableModel calModel = new DefaultTableModel();
d.setBounds(20, 200, 500, 350);
for (int x = 0; x < button.length; x++) {
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if (x > 6)
button[x].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
day = button[selection].getActionCommand();
}
});
if (x < 7) {
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
d.add(button[x]);
}
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month--;
displayDate();
}
});
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month++;
displayDate();
}
});
displayDate();
}
public void displayDate() {
for (int x = 7; x < button.length; x++)
button[x].setText("");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"MMMM yyyy");
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, 1);
int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
button[x].setText("" + day);
l.setText(sdf.format(cal.getTime()));
}
}
Can someone please help me?

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