Problems using 2 JButtons in Java - java

I'm making a program to return a value, from two entered numbers, with one of two calculations.
But I can't get the second JButton to work. When i enter two values and click the "Get Alternative Definition", it returns nothing.
I've tested my AltDefinition Class and it is working proberly.
Can anyone help me find the problem in this code?:
public class BinomialCoefficient implements ActionListener {
private JTextField tJTextFieldResult;
private JTextField tTextNumber1;
private JTextField tTextNumber2;
public BinomialCoefficient(String pString) {
JFrame tJFrame = new JFrame(pString);
tJTextFieldResult = new JTextField("Enter value n and k. Note: 0 < k < n < 60", 20);
tTextNumber1 = new JTextField("n", 10);
tTextNumber2 = new JTextField("k", 10);
JButton tButton1 = new JButton("Get BinomialCoefficient");
JButton tButton2 = new JButton("Get Alternative Definition");
tButton1.addActionListener(this);
tButton2.addActionListener(this);
Container tContentPane = tJFrame.getContentPane();
tContentPane.add(tJTextFieldResult, BorderLayout.NORTH);
tContentPane.add(tTextNumber1, BorderLayout.WEST);
tContentPane.add(tTextNumber2, BorderLayout.EAST);
tContentPane.add(tButton1, BorderLayout.CENTER);
tContentPane.add(tButton2, BorderLayout.SOUTH);
tJFrame.pack();
tJFrame.setVisible(true);
}
public void actionPerformed(ActionEvent pActionEvent) {
String tCommand = pActionEvent.getActionCommand();
int number1 = new Integer(tTextNumber1.getText()).intValue();
int number2 = new Integer(tTextNumber2.getText()).intValue();
if (number1 > 60 || number2 > 60 || number1 <= 0 || number2 <= 0 || number1 < number2 ) {
tJTextFieldResult.setText("Please follow these conditions: 0 < k < n < 60");
} else if
(tCommand.equals("Get BinomialCoefficient")) {
try {
final double Result = Conditions.GetBiCoefficient(number1, number2);
tJTextFieldResult.setText("" + Result);
} catch (IOException e) {
e.printStackTrace();
}
if (number1 > 60 || number2 > 60 || number1 <= 0 || number2 <= 0 || number1 < number2 ) {
tJTextFieldResult.setText("Please follow these conditions: 0 < k < n < 60");
} else if
(tCommand.equals("Get Alternative Definition")) {
try {
final double Result2 = AltDefinition.GetAltDefinition(number1, number2);
tJTextFieldResult.setText("" + Result2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

You have if (tCommand.equals("Get Alternative Definition")) { inside your other if that checks if it equals "Get BinomialCoefficient".
If it ever equals "Get BinomialCoefficient", then it obviously can't equal "Get Alternative Definition". Rethink the flow of your action handler.
Edit: it actually looks like you just forgot a closing brace. This should correct it:
public void actionPerformed(ActionEvent pActionEvent) {
String tCommand = pActionEvent.getActionCommand();
int number1 = new Integer(tTextNumber1.getText()).intValue();
int number2 = new Integer(tTextNumber2.getText()).intValue();
if (number1 > 60 || number2 > 60 || number1 <= 0 || number2 <= 0 || number1 < number2) {
tJTextFieldResult.setText("Please follow these conditions: 0 < k < n < 60");
} else if (tCommand.equals("Get BinomialCoefficient")) {
try {
final double Result = Conditions.GetBiCoefficient(number1, number2);
tJTextFieldResult.setText("" + Result);
} catch (IOException e) {
e.printStackTrace();
}
} else if (tCommand.equals("Get Alternative Definition")) {
try {
final double Result2 = AltDefinition.GetAltDefinition(number1, number2);
tJTextFieldResult.setText("" + Result2);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Prime factorization using GUI (swing/awt)

This code uses Swing and awt to compute prime factorization, the code works, but it shows only one prime factor, for example: if i compute 56 the answer is just 7, how can i fix it?
thanks in advance
calculate6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get values from text fields
try {
int a = Integer.parseInt(input1.getText());
result.setText(String.valueOf(a + " "));
for (int i = 2; i <= a; i++) {
while (a % i == 0) {
result.setText(String.valueOf(i + " "));
// System.out.println(i + " ");
a = a / i;
}
}
if (a < 1)
result.setText(String.valueOf(a + " "));
// System.out.println(a + " ");
}
catch (Exception f) {
JOptionPane.showMessageDialog(rootPane, "ERROR: " + (f.getMessage()));
}
String aField = input1.getText();
if (e.getSource() == calculate6) {
if ("".equals(aField)) {
String emptyFieldWarning;
emptyFieldWarning = "One field is empty!";
JOptionPane.showMessageDialog(rootPane, emptyFieldWarning);
}
}
}
});
Edit 1: i have changed the operation part
Your Swing part is fine. If you just try to execute
int a = 56;
for(int i = 2; i< a; i++) {
while (a % i == 0) {
a = a / i;
}
}
System.out.println(a);
you get 7,so the problem is in this part, you shoul look over here
Problem is in the while loop. It is not accumulating the factors. Try this getPrimeFactors() in this sample program.
import java.util.*;
public class PrimeFactors {
public static void main(String[] args) {
System.out.println("56 -> " + PrimeFactors.getPrimeFactors(56));
System.out.println("30 -> " + PrimeFactors.getPrimeFactors(30));
System.out.println("154 -> " + PrimeFactors.getPrimeFactors(154));
}
public static List<Integer> getPrimeFactors(int input) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i <= input; i++) {
while (input%i == 0) {
input = input/i;
factors.add(i);
}
}
return factors;
}
}
public static final IntFunction<String> getPrimeFactorsAsString = num -> {
List<Integer> res = new ArrayList<>();
for (int i = 2, sqrt = (int)Math.sqrt(num); i <= sqrt; i++) {
while (num % i == 0) {
res.add(i);
num /= i;
}
}
return res.stream().map(String::valueOf).collect(Collectors.joining(" "));
};
Demo
System.out.println(getPrimeFactorsAsString.apply(56)); // 2 2 2 7
System.out.println(getPrimeFactorsAsString.apply(660)); // 2 2 3 5 11

Main method in different class can't detect button press

I'm making a program for practice and it's basically simulating winning/losing Powerball tickets. Anyways, the main class is in launchPowerBall.java and the button that I am trying to detect when clicked is in PowerBallGUI.java. The button works by itself, however, the main in launchPowerBall.java isn't able to detect it even though I set up myself a few setters and getters. Any clue what alternative I can do instead? Because it seems as though even though I run it through a while(true) loop and I keep pressing the button, there seems to be no detection from the main method.
Here's the action listener for the JButton:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
Here's what I'm trying to do for the main method:
public static void main(String[] args) throws InterruptedException {
// Build the GUI object
PowerBallGUI GUI = new PowerBallGUI();
GUI.buildGUI();
//GUI.setTextArea("banana");
// Build the PowerBall object
PowerBall roll = new PowerBall();
while(true) {
if (GUI.getJButton().getModel().isPressed()) {
System.out.println("TEST");
}
}
}
Here's the three files if you need to see my code:
1) https://gist.github.com/anonymous/e5950413470202cd1ac6d24e238ff693
2) https://gist.github.com/anonymous/773e4e4454a79c057da78eed038fade1
3) https://gist.github.com/anonymous/82335e634c1f84607d3021b4d683cc65
Powerball...
public class PowerBall {
private int[] numbers = {0, 0, 0, 0, 0};
private int[] lotteryNumbers = {0, 0, 0, 0, 0};
private int powerBall;
private int lotteryPowerBall;
private double balance;
private double winnings;
/*** Constructor Methods ***/
public PowerBall() {
powerBall = 0;
balance = 1000;
winnings = 0;
}
/*** Mutator Methods ***/
public void randomize() {
int i;
int highestNumber = 59;
int highestPowerball = 32;
int temp = 0;
for (i = 0; i < numbers.length; i++) {
// Choose a random number
temp = (int)(Math.random() * highestNumber);
numbers[i] = temp;
}
// Choose a random Powerball number
powerBall = (int)(Math.random() * highestPowerball);
// Choose the lottery numbers
for (i = 0; i < lotteryNumbers.length; i++) {
temp = (int)(Math.random() * highestNumber);
lotteryNumbers[i] = temp;
}
lotteryPowerBall = (int)(Math.random() * highestPowerball);
}
public void calculate() {
int matches = 0;
int powerballMatches = 0;
if (balance > 0) {
// Check to see if there are any matches between the two sets of numbers
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < lotteryNumbers.length; j++) {
if (numbers[i] == lotteryNumbers[j]) {
matches++;
}
}
}
// Check to see if the two different powerball numbers match
if (powerBall == lotteryPowerBall) {
powerballMatches = 1;
}
// Calculate the balance/winnings if there were any matches
if (matches == 0 && powerballMatches == 0) {
balance = balance - 2;
winnings = winnings - 2;
} else if (matches == 0 && powerballMatches == 1) {
balance = balance + 4;
winnings = winnings + 4;
} else if (matches == 0 && powerballMatches == 0 || matches == 1 && powerballMatches == 0) {
balance = balance - 2;
winnings = winnings - 2;
} else if (matches == 2 && powerballMatches == 1) {
balance = balance + 7;
winnings = winnings + 7;
} else if (matches == 3 && powerballMatches == 0) {
balance = balance + 7;
winnings = winnings + 7;
} else if (matches == 3 && powerballMatches == 1) {
balance = balance + 100;
winnings = winnings + 100;
} else if (matches == 4 && powerballMatches == 0) {
balance = balance + 100;
winnings = winnings + 100;
} else if (matches == 4 && powerballMatches == 1) {
balance = balance + 50000;
winnings = winnings + 50000;
} else if (matches == 5 && powerballMatches == 0) {
balance = balance + 1000000;
winnings = winnings + 1000000;
} else if (matches == 5 && powerballMatches == 1) {
balance = balance + 10000000;
winnings = winnings + 10000000;
}
//System.out.println("There is currently " + matches + " number matches.");
//System.out.println("There is currently " + powerballMatches + " powerball number matches.\n");
} else {
System.out.println("YOU ARE BROKE!");
}
}
/*** Accessor/Observor Methods ***/
public void displayBalance() {
System.out.print("Your balance is at: $");
System.out.printf("%.2f", balance);
}
public void displayWinnings() {
System.out.print("\nYou have currently won: $");
System.out.printf("%.2f", winnings);
System.out.println("\n");
}
public String toString() {
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
if (numbers.length == lotteryNumbers.length) {
for (int i = 0; i < numbers.length; i++) {
if (i < numbers.length - 1) {
builder.append(numbers[i] + ", ");
builder2.append(lotteryNumbers[i] + ", ");
} else {
builder.append(numbers[i] + " + ");
builder2.append(lotteryNumbers[i] + " + ");
}
}
} else {
return "ERROR: Numbers max set of numbers doesn't match Lottery Numbers max set of numbers!\n";
}
return "Your set of numbers were: " + builder + Integer.toString(powerBall) +
"\nThe powerball numbers were: " + builder2 + lotteryPowerBall;
}
}
Launcher
public class launchPowerBall {
public static void main(String[] args) throws InterruptedException {
// Build the GUI object
PowerBallGUI GUI = new PowerBallGUI();
GUI.buildGUI();
//GUI.setTextArea("banana");
// Build the PowerBall object
PowerBall roll = new PowerBall();
while(true) {
if (GUI.getJButton().getModel().isPressed()) {
System.out.println("TEST");
}
}
//System.out.println("TOO LATE!");
//while (true) {
/*roll.randomize();
System.out.println(roll.toString());
roll.calculate();
roll.displayBalance();
roll.displayWinnings();
Thread.sleep(500); */
//}
}
}
GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PowerBallGUI {
private JButton start = new JButton("Launch the Powerball!");
private boolean buttonPressed = false;
private String outText;
/*** Constructor Methods ***/
public PowerBallGUI() {
#SuppressWarnings("unused")
JTextArea outputText = new JTextArea("Press the 'Launch the Powerball' button to start!");
}
/*** Setters ***/
/*** Sets the JTextArea object ***/
public void setTextArea (String str) {
this.outText = str;
}
public void setButtonPressed (Boolean bool) {
this.buttonPressed = bool;
}
/*** Getters ***/
public Boolean getButtonPressed() {
return this.buttonPressed;
}
public JButton getJButton() {
return this.start;
}
/*** Builds the GUI ***/
public void buildGUI() {
// Create the Java Frame itself
JFrame frame = new JFrame("Can YOU win the Powerball? v1.0 (Programmed by: Josh Yang)");
// Sets the default close operation of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the size of the frame
frame.setSize(800, 500);
// Sets the location of the frame
centerGUI(frame);
// Allows the frame to be seen
frame.setVisible(true);
// Disables frame resizing
//frame.setResizable(false);
// Create the Java Panel itself
JPanel panel = new JPanel();
JPanel contentPanel = new JPanel();
JPanel launchPanel = new JPanel();
// Sets the sides of the Java panels
panel.setSize(800, 150);
// Set the panel background color
panel.setBackground(Color.YELLOW);
contentPanel.setBackground(Color.YELLOW);
launchPanel.setBackground(Color.PINK);
// Add the panel onto the frame
frame.add(panel, "North");
frame.add(contentPanel, BorderLayout.CENTER);
frame.add(launchPanel, BorderLayout.SOUTH);
// Set top panel's preferred size dimensions
panel.setPreferredSize(new Dimension(800, 100));
// Adds components onto the panel
JLabel title = new JLabel("Can YOU win the lottery? v1.0", SwingConstants.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 25));
panel.add(title);
String text = "Basically, we start you off at $1000 and buy tickets in increments of $2 until you win big (if you do, that is)!";
JLabel description = new JLabel();
description.setText(text);
description.setFont(new Font("Serif", Font.PLAIN, 16));
panel.add(description);
// ContentPanel area
JLabel cDescription = new JLabel("Output: ");
contentPanel.add(cDescription);
JTextArea outputText = new JTextArea(17, 60);
outputText.setBackground(Color.PINK);
outputText.setEditable(false);
outputText.setText("Press the 'Launch the Powerball' button to start!");
contentPanel.add(outputText);
start.setLocation(100, 100);
launchPanel.add(start);
// Add an action listener to the JButton
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
frame.revalidate();
//frame.pack();
}
/*** Centers the GUI based on screen size ***/
public static void centerGUI(Window frame) {
// Gets the size of the screen
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
// Set the frame location based on x and y
frame.setLocation(x, y);
}
}
The simple solution is to take the functionality you're "trying" to execute in the main method and put in the ActionListener...
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
PowerBall roll = new PowerBall();
roll.randomize();
System.out.println(roll.toString());
roll.calculate();
roll.displayBalance();
roll.displayWinnings();
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
If you "really" want to do more work in the main, you will need to generate some kind of observer pattern which can notified when something occurs.
You could put one on Powerball so it could notify you of a status change or on the GUI which notify you that the start button was pressed

Is it possible to merge these two do loops

I've tried merging the two loops into one do loop, but every time I enter an invalid value it doesn't prompt me the error message and ask to enter the value again. Instead it just moves on to the next prompt statement.
do {
try {
dependents = Integer.parseInt(JOptionPane.showInputDialog("number of dependents:"));
}
catch (NumberFormatException e) {
dependents = MIN_DEPENDENTS - 1;
}
if (dependents < MIN_DEPENDENTS || dependents > MAX_DEPENDENTS) {
JOptionPane.showMessageDialog(null, "Number of dependents must be between 0 and 9.");
}
} while (dependents < MIN_DEPENDENTS || dependents > MAX_DEPENDENTS);
do {
try {
income = Double.parseDouble(JOptionPane.showInputDialog("amount of income:"));
}
catch (NumberFormatException e) {
income = MIN_INCOME - 1;
}
if (income < MIN_INCOME || income > MAX_INCOME) {
JOptionPane.showMessageDialog(null, "income must be between $0 and $999,999.");
}
} while (income < MIN_INCOME || income > MAX_INCOME);
No, but you could create some sort of GetInput function and pass in min, max, promptText, and errorText. This would save you duplicating the code.
dependents = getInput(MIN_DEPENDENTS, MAX_DEPENDENTS,"number of dependents:","Number of dependents must be between 0 and 9.")
income = getInput(MIN_INCOME,MAX_INCOME,"amount of income:","income must be between $0 and $999,999.")
private double getInput(double min, double max, String promptText, String errorText) {
double result = 0.0;
do {
try {
result = Double.parseDouble(JOptionPane.showInputDialog(promptText));
}
catch (NumberFormatException e) {
result = min - 1;
}
if (result < min || result > max) {
JOptionPane.showMessageDialog(null, errorText);
}
} while (result < min || result > max);
return result;
}
Dan, you need to put below lined in your catch block to show error message and prompt again for input.
catch (NumberFormatException e) {
dependents = MIN_DEPENDENTS - 1;
JOptionPane.showMessageDialog(null, "Number of dependents must be between 0 and 9.");
dependents = Integer.parseInt(JOptionPane.showInputDialog("number of dependents:"));
}
Another option could to main list of input in array and then use it in while loop
Object[][] input = {
{"number of dependents", MIN_DEPENDENTS, MAX_DEPENDENTS},
{"amount of income", MIN_INCOME, MAX_INCOME},
};
int index = 0;
int value, min, max;
do {
Object[] inputDetails = input[index];
String label = inputDetails[0].toString();
min = Integer.valueOf(inputDetails[1].toString());
max = Integer.valueOf(inputDetails[2].toString());
try {
value = Integer.parseInt(JOptionPane.showInputDialog(label));
} catch (NumberFormatException e) {
value = min - 1;
}
if (value < min || value > max) {
JOptionPane.showMessageDialog(null, String.format("%s must be between %s and %s", label, min, max));
} else {
index++;
}
} while ((value < min || value > max) || index < input.length);

JOptionPane.showMessageDialog keeps reappearing

My code is supposed to ensure that users only enter a binary string. Everything goes right and in order if I enter a correct binary number (1, 0). But when I enter a wrong number (alphabet or number other than 0 and 1) JOptionPane.ShowMessageDialog appears showing the error message, and when I click "OK" or "Cross" Button it reappears again. So to close the app I have to use the process manager to kill "java.exe".
Here is the complete code for my app:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Bn extends JFrame {
private JLabel l1;
private JLabel l2;
private JLabel l3;
private JTextField tf;
private JButton oc;
private JButton hd;
private JButton dc;
public Bn() {
setTitle("Binary Conversion");
setSize(350 , 190);
setResizable(false);
setLocation(720 , 200);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER, 25, 10));
l1 = new JLabel(">>>>>>>>BINARY CONVERSION<<<<<<<<");
l2 = new JLabel("Enter The Number:");
l3 = new JLabel(" Convert to: ");
tf = new JTextField(25);
oc = new JButton("Octal");
hd = new JButton("Hexa Decimal");
dc = new JButton("Decimal");
add(l1); // Binary conversion
add(l2); // Enter The Number
add(tf); // Text Field
add(l3); // Conver to
add(oc); // Octal
add(hd); // Hexa Decimal
add(dc); // Decimal
oc.addActionListener(new cvr());
hd.addActionListener(new cvr());
dc.addActionListener(new cvr());
setVisible(true);
}
void res()
{
int b = 0;
String num = tf.getText();
int i , l;
l = num.length();
char ch;
do
{
for (i=0 ; i<l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);
}
void occ()
{
res();
String num = tf.getText();
long dec = Long.parseLong(num,2);
String oct = Long.toOctalString(dec);
JOptionPane.showMessageDialog(null, "Octal equivalent is: "+ oct);
}
void hdc()
{
res();
String num = tf.getText();
long dec = Integer.parseInt(num,2);
String hex = Long.toHexString(dec);
JOptionPane.showMessageDialog(null, "Hexa Decimal equivalent is: "+ hex);
}
void dcc()
{
res();
String num = tf.getText();
long decimal = 0, temp, i = 0;
temp = Long.parseLong(num);
while (temp != 0) {
long r = temp % 10;
long value = r * (int)Math.pow(2, i);
i++;
decimal = decimal + value;
temp /= 10;
}
JOptionPane.showMessageDialog(null, "Decimal equivalent is: "+ decimal);
}
private class cvr implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == oc)
{
occ();
}
if (e.getSource() == hd)
{
hdc();
}
if (e.getSource() == dc)
{
dcc();
}
}
}
public static void main(String args[])
{
Bn obj = new Bn();
}
}
The code for JOptionPane is located in void res() method. How can I close this Dialog pane so I may reenter the value for input?
Remove the do { } while loop
do
{
for (i=0 ; i < l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);

Implementing ActionListener in the Following Code Inside

I'm having some trouble with my age calculating program on Java. It works fine when I preset the birth year, birth month and birth date values but when I try to have the user input their own birthdate into the text field and then try to work with those values, I just reach a dead-end. I tried asking on Yahoo Answers and the hint I got was "The return value of getActionCommand() is a string while the result is a JLabel. Can you compare them?" I'm not exactly sure what to do with that hint.
Here's what I have and the way I attempted to implement the whole "user input" idea. I'm pretty sure my coding is messy and inefficient, so bear with that please. I'd appreciate any help!
//Date: April 11, 2012
//Description: Calculates the age in terms of days depending on your birthdate.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AgeCalculator extends Frame implements ActionListener {
JButton equal;
JTextField year, month, day;
JLabel result, first, second, third;
JFrame frame;
JPanel panel;
static int totaldaysalive;
static int daysaliveyr;
static int daysalivem;
static int birthyr;
static int birthm;
static int birthd;
static int currentyr = 2012;
public AgeCalculator(){
gui();
}
public void gui(){
frame = new JFrame ("Age Calculator");
panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.LIGHT_GRAY);
GridBagConstraints x = new GridBagConstraints();
equal = new JButton ("Get Result");
x.insets = new Insets(3,0,3,0);
first = new JLabel("Year ");
x.gridx = 0;
x.gridx = 0;
panel.add(first, x);
year = new JTextField(10);
x.gridx = 5;
x.gridy = 0;
x.gridwidth = 3;
panel.add(year, x);
second = new JLabel ("Month ");
x.gridx = 0;
x.gridy = 1;
panel.add(second,x);
month = new JTextField(10);
x.gridx = 5;
x.gridy = 1;
x.gridwidth = 3;
panel.add(month,x);
third = new JLabel ("Day ");
x.gridx = 0;
x.gridy = 2;
panel.add(third,x);
day = new JTextField(10);
x.gridx = 5;
x.gridy = 2;
x.gridwidth = 3;
panel.add(day,x);
x.gridx = 6;
x.gridy = 3;
panel.add(equal,x);
result = new JLabel ("");
x.gridx = 5;
x.gridy = 5;
panel.add(result,x);
frame.add(panel);
frame.setVisible(true);
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calc e = new Calc();
equal.addActionListener(e);
year.addActionListener(e);
month.addActionListener(e);
day.addActionListener(e);
}
class Calc implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
birthyr = Integer.parseInt(year.getText());
} catch (NumberFormatException a) {
result.setText("Illegal data for first field.");
result.setForeground(Color.red);
return;
}
try {
birthm = Integer.parseInt(month.getText());
} catch (NumberFormatException a) {
result.setText("Illegal data for second field.");
result.setForeground(Color.red);
return;
}
try {
birthd = Integer.parseInt(day.getText());
} catch (NumberFormatException a) {
result.setText("Illegal data for third field.");
result.setForeground(Color.red);
return;
}
if (e.getActionCommand().equals (equal)){
totaldaysalive = ageCalcYr() + ageCalcM() + birthd;
result.setText(Integer.toString(totaldaysalive));
}
}
public int ageCalcYr(){
for (int i = birthyr; i <= currentyr; i++){
if ((i % 4 == 0) && (!(i % 100 == 0) || (i % 400 == 0))){
daysaliveyr = daysaliveyr + 366;
}
else {
daysaliveyr = daysaliveyr + 365;
}
}
return daysaliveyr;
}
public int ageCalcM(){
if (birthm == 1){
daysalivem = daysalivem + 0;
}
else if (birthm == 2){
daysalivem = daysalivem + 30;
}
else if (birthm == 3){
daysalivem = daysalivem + 60;
}
else if (birthm == 4){
daysalivem = daysalivem + 90;
}
else if (birthm == 5){
daysalivem = daysalivem + 120;
}
else if (birthm == 6){
daysalivem = daysalivem + 150;
}
else if (birthm == 7){
daysalivem = daysalivem + 180;
}
else if (birthm == 8){
daysalivem = daysalivem + 210;
}
else if (birthm == 9){
daysalivem = daysalivem + 240;
}
else if (birthm == 10){
daysalivem = daysalivem + 270;
}
else if (birthm == 11){
daysalivem = daysalivem + 300;
}
else if (birthm == 12){
daysalivem = daysalivem + 330;
}
return daysalivem;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
AgeCalculator gui = new AgeCalculator();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Fast healing:
if (e.getActionCommand ().equals ("Get Result")) { // equal)) {
totaldaysalive = ageCalcYr () + ageCalcM () + birthd;
result.setText (Integer.toString (totaldaysalive));
}
If you have some time, I can post you 20 improvements.
You extend Frame,
impl. ActionListener, but meanwhile AgeCalculator has a JFrame (which is better in a SwingContext than Frame, which is AWT) and has a seperate Actionlistener which is used.
Remove the declaration, and the the overriding method in the end.
public class AgeCalculator // extends Frame implements ActionListener
There follows a block of visual components and other attributes, the later ones are static - which prohibits using of 2 AgeCalculators on the same JVM. That's surely not a restriction by intent.
Don't make something static to shut up the compiler.
Make everything private, if you aren't sure you want to expose it.
Avoid Attributes where possible.
When will you ever retouch a Label?
JButton equal;
JTextField year, month, day;
JLabel result, ...
...
static int birthd;
static int currentyr = 2012;
Use simplified addition where appropriate:
daysaliveyr += 366;
To calc the days for month, pass the birthyr and the birthm as parameter:
int totaldaysalive = ageCalcYr (birthyr) + ageCalcM (birthm) + birthd;
result.setText (Integer.toString (totaldaysalive));
The livetime of the variable totaldaysalive can be reduced to 2 lines - a very small scope to search for an error, if there is any.
public int ageCalcM (int birthm) {
int daysalivem = 0;
if (birthm == 2) {
daysalivem += 30;
}
else if (birthm == 3) {
daysalivem += 60;
}
In the current state, ageCalcM is a provisorium. Else you could just say daysalivem = (birthm - 1) * 30;
Shorter code:
public int ageCalcM (int birthm) {
if (birthm == 2) {
return 30;
}
else if (birthm == 3) {
return 60;
}
However, such mass manipulation in stupid repetition can be solved with an simple array:
public int ageCalcM (int birthm) {
int[] mdays = {0, 30, 60, 90, ...};
return mdays [birthm];
}
In the main-Method you create an instance 'gui', which is never used. This is all you need:
public static void main (String [] args) {
new AgeCalculator ();
}
Gui, btw. is a bad name, if you already have a method of said name.
Since that method is never used, just move the whole thing into the ctor.
year/month/date don't need the ActionListener.
Other layouts are much better suited.
We need another calender reform to make your program work.
Input should not only be checked to be int, but valid month etc.
The actual date isn't used.
What is left?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AgeCalculator
{
JTextField year, month, day;
JLabel result;
public AgeCalculator () {
JFrame frame = new JFrame ("Age Calculator");
JPanel panel = new JPanel (new GridBagLayout ());
panel.setBackground (Color.LIGHT_GRAY);
GridBagConstraints x = new GridBagConstraints ();
JButton equal = new JButton ("Get Result");
x.insets = new Insets (3, 0, 3, 0);
JLabel first = new JLabel ("Year ");
// two times gridx = 0 here?
x.gridx = 0;
x.gridx = 0;
panel.add (first, x);
year = new JTextField (10);
x.gridx = 5;
x.gridy = 0;
x.gridwidth = 3;
panel.add (year, x);
JLabel second = new JLabel ("Month ");
x.gridx = 0;
x.gridy = 1;
panel.add (second, x);
month = new JTextField (10);
x.gridx = 5;
x.gridy = 1;
x.gridwidth = 3;
panel.add (month, x);
JLabel third = new JLabel ("Day ");
x.gridx = 0;
x.gridy = 2;
panel.add (third, x);
day = new JTextField (10);
x.gridx = 5;
x.gridy = 2;
x.gridwidth = 3;
panel.add (day, x);
x.gridx = 6;
x.gridy = 3;
panel.add (equal, x);
result = new JLabel ("");
x.gridx = 5;
x.gridy = 5;
panel.add (result, x);
frame.add (panel);
frame.setVisible (true);
frame.setSize (350, 350);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Calc e = new Calc ();
equal.addActionListener (e);
}
class Calc implements ActionListener {
public void actionPerformed (ActionEvent e) {
int birthyr;
int birthm;
int birthd;
try {
birthyr = Integer.parseInt (year.getText ());
} catch (NumberFormatException a) {
result.setText ("Illegal data for first field.");
result.setForeground (Color.red);
return;
}
try {
birthm = Integer.parseInt (month.getText ());
} catch (NumberFormatException a) {
result.setText ("Illegal data for second field.");
result.setForeground (Color.red);
return;
}
try {
birthd = Integer.parseInt (day.getText ());
} catch (NumberFormatException a) {
result.setText ("Illegal data for third field.");
result.setForeground (Color.red);
return;
}
if (e.getActionCommand ().equals ("Get Result")) { // equal)) {
int totaldaysalive = ageCalcYr (birthyr) + ageCalcM (birthm) + birthd;
result.setText (Integer.toString (totaldaysalive));
}
}
public int ageCalcYr (int birthyr) {
int currentyr = 2012;
int daysaliveyr = 0;
for (int i = birthyr; i <= currentyr; i++) {
if ((i % 4 == 0) && (! (i % 100 == 0) || (i % 400 == 0))) {
daysaliveyr += 366;
}
else {
daysaliveyr += 365;
}
}
return daysaliveyr;
}
public int ageCalcM (int birthm) {
int[] mdays = {0, 30, 60, 90, 120};
return mdays [birthm];
}
}
public static void main (String [] args) {
new AgeCalculator ();
}
}
Since you're using a button to kick off the calculation, only register an action listener on that button. Inside the action performed method read, parse and calculate the age in days.
I think you want to do equal.addMouseListener(e). Of course you'll have to change Calc to implement MouseListener. You'll probably only have to actually write the mouseClicked(MouseEvent) method. All of the others are for more specific things than what you're after.
That will respond to a click event on your button. I don't think you want any other listeners. If so, they should be KeyListeners or something other than ActionListeners.
On a side note, It's hard for me to see because your indentation is off, but I can't really tell why your int fields are static. I think that's probably unnecessary.

Categories