Exception in thread "main" IllegalArgumentException: adding container's parent to itself - java

I just started learning programming and am trying to create a program that calculates the income tax at 20%. the program compiles but keeps getting errors. The error states
Exception in thread "main" java.lang.IllegalArgumentException: adding container's parent to itself
I don't understand what to change.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class IncomeTax extends JFrame
{
// declarations
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
Color light_gray = new Color(192, 192, 192);
DecimalFormat currency;
JLabel grossIncomeJLabel;
JTextField grossIncomeJTextField;
JLabel amountTaxedJLabel;
JTextField amountTaxedJTextField;
JTextField currencyJTextField;
JLabel amountDeductedJLabel;
JTextField amountDeductedJTextField;
JLabel netIncomeJLabel;
JTextField netIncomeJTextField;
JButton enterJButton;
JButton clearJButton;
double grossIncome;
double amountTaxed;
double amountDeducted;
double netIncome;
public IncomeTax()
{
createUserInterface();
}
public void createUserInterface()
{
Container contentPane = getContentPane();
contentPane.setBackground(white);
contentPane.setLayout(null);
// initialize components
// input
grossIncomeJLabel = new JLabel ();
grossIncomeJLabel.setBounds (50, 20, 150, 20);
grossIncomeJLabel.setFont(new Font("Default", Font.PLAIN, 12));
grossIncomeJLabel.setText ("Enter Gross Income:");
grossIncomeJLabel.setForeground(black);
grossIncomeJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(grossIncomeJLabel);
grossIncomeJTextField = new JTextField();
grossIncomeJTextField.setBounds(200, 20, 100, 20);
grossIncomeJTextField.setFont(new Font("Default", Font.PLAIN, 12));
grossIncomeJTextField.setHorizontalAlignment(JTextField.CENTER);
grossIncomeJTextField.setForeground(black);
grossIncomeJTextField.setBackground(white);
grossIncomeJTextField.setEditable(true);
contentPane.add(grossIncomeJTextField);
//outputs
amountTaxedJLabel = new JLabel();
amountTaxedJLabel.setBounds(50, 50, 150, 20);
amountTaxedJLabel.setFont(new Font("Default", Font.PLAIN, 12));
amountTaxedJLabel.setText("Amount Taxed");
amountTaxedJLabel.setForeground(black);
amountTaxedJLabel.setHorizontalAlignment(JLabel.LEFT);
amountTaxedJLabel.add(amountTaxedJLabel);
amountTaxedJTextField = new JTextField();
amountTaxedJTextField.setBounds(200, 50, 100, 20);
amountTaxedJTextField.setFont(new Font("Default", Font.PLAIN, 12));
amountTaxedJTextField.setHorizontalAlignment(JTextField.CENTER);
amountTaxedJTextField.setForeground(black);
amountTaxedJTextField.setBackground(white);
amountTaxedJTextField.setEditable(false);
contentPane.add(amountTaxedJTextField);
amountDeductedJLabel = new JLabel();
amountDeductedJLabel.setBounds(50, 80, 150, 20);
amountDeductedJLabel.setFont(new Font("Default", Font.PLAIN, 12));
amountDeductedJLabel.setText("Amount Deducted:");
amountDeductedJLabel.setForeground(black);
amountDeductedJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(amountDeductedJLabel);
amountDeductedJTextField = new JTextField();
amountDeductedJTextField.setBounds(200, 80, 100, 20);
amountDeductedJTextField.setFont(new Font("Default", Font.PLAIN, 12));
amountDeductedJTextField.setHorizontalAlignment(JTextField.CENTER);
amountDeductedJTextField.setForeground(black);
amountDeductedJTextField.setBackground(white);
amountDeductedJTextField.setEditable(false);
contentPane.add(amountDeductedJTextField);
netIncomeJLabel = new JLabel();
netIncomeJLabel.setBounds(50, 110, 150, 20);
netIncomeJLabel.setFont(new Font("Default", Font.PLAIN, 12));
netIncomeJLabel.setText("Net Income:");
netIncomeJLabel.setForeground(black);
netIncomeJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(netIncomeJLabel);
netIncomeJTextField = new JTextField();
netIncomeJTextField.setBounds(200, 110, 100, 20);
netIncomeJTextField.setFont(new Font("Default", Font.PLAIN, 12));
netIncomeJTextField.setHorizontalAlignment(JTextField.CENTER);
netIncomeJTextField.setForeground(black);
netIncomeJTextField.setBackground(white);
netIncomeJTextField.setEditable(false);
contentPane.add(netIncomeJTextField);
// control
enterJButton = new JButton();
enterJButton.setBounds(50, 210, 100, 20);
enterJButton.setFont(new Font("Default", Font.PLAIN, 12));
enterJButton.setText("Enter");
enterJButton.setForeground(black);
enterJButton.setBackground(white);
contentPane.add(enterJButton);
enterJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
enterJButtonActionPerformed(event);
}
}
);
clearJButton = new JButton();
clearJButton.setBounds(200, 210, 100, 20);
clearJButton.setFont(new Font("Default", Font.PLAIN, 12));
clearJButton.setText("Clear");
clearJButton.setForeground(black);
clearJButton.setBackground(white);
contentPane.add(clearJButton);
clearJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clearJButtonActionPerformed(event);
}
}
);
// set properties of application’s window
setTitle("Income Tax"); // set title
setSize( 400, 400 ); // set window size
setVisible(true); // display window
}
// main method
public static void main(String[] args)
{
IncomeTax application = new IncomeTax();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void enterJButtonActionPerformed(ActionEvent event)
{
// get input
grossIncome = Double.parseDouble(grossIncomeJTextField.getText());
// process data
final double Tax_Rate = .20;
amountTaxed = Tax_Rate;
amountDeducted = grossIncome * Tax_Rate;
netIncome = grossIncome - amountDeducted;
//display results
currency = new DecimalFormat("$0.00");
amountTaxedJTextField.setText("" + currency.format(amountTaxed));
amountDeductedJTextField.setText("" + currency.format(amountDeducted));
netIncomeJTextField.setText("" + currency.format(netIncome));
}
public void clearJButtonActionPerformed(ActionEvent event)
{
grossIncomeJTextField.setText("");
grossIncomeJTextField.requestFocusInWindow();
amountTaxedJTextField.setText("");
amountDeductedJTextField.setText("");
netIncomeJTextField.setText("");
}
}

Here
amountTaxedJLabel.add(amountTaxedJLabel);
I think you meant
contentPane.add(amountTaxedJLabel);
In the prior, you are adding a view to itself.
In the later, you are adding it to your contentPane.

Related

txtDisplay cannot be resolved in java eclipse

Making a calculator right now and for some reason, txtdisplay is not working. When I run the program and click number 7. I get error messages. how do i fix it?
Here is the code. I've recently been having problems with eclipse ever since I downloaded it on a new computer. I have looked for a solution to the problem and tried what eclipse suggsted and what the answers to a similar question asked and it's still not working right now.
package Calculators;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class Calculator {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Calculator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 266, 337);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 11, 211, 32);
frame.getContentPane().add(textField);
textField.setColumns(10);
//row one
JButton btn7 = new JButton("7");
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = txtDisplay.getText() + btn7.getText();
txtDisplay.setText(EnterNumber);
}
});
btn7.setBackground(Color.CYAN);
btn7.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn7.setBounds(10, 54, 50, 50);
frame.getContentPane().add(btn7);
JButton btn8 = new JButton("8");
btn8.setBackground(Color.YELLOW);
btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btn8.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn8.setBounds(70, 54, 50, 50);
frame.getContentPane().add(btn8);
JButton btn9 = new JButton("9");
btn9.setBackground(Color.ORANGE);
btn9.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn9.setBounds(130, 54, 50, 50);
frame.getContentPane().add(btn9);
JButton btnPlus = new JButton("+");
btnPlus.setBackground(Color.PINK);
btnPlus.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnPlus.setBounds(190, 54, 50, 50);
frame.getContentPane().add(btnPlus);
// row two
JButton btn4 = new JButton("4");
btn4.setBackground(Color.CYAN);
btn4.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn4.setBounds(10, 114, 50, 50);
frame.getContentPane().add(btn4);
JButton btn5 = new JButton("5");
btn5.setBackground(Color.YELLOW);
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btn5.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn5.setBounds(70, 114, 50, 50);
frame.getContentPane().add(btn5);
JButton btn6 = new JButton("6");
btn6.setBackground(Color.ORANGE);
btn6.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn6.setBounds(130, 114, 50, 50);
frame.getContentPane().add(btn6);
JButton btnMinus = new JButton("-");
btnMinus.setBackground(Color.PINK);
btnMinus.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnMinus.setBounds(190, 114, 50, 50);
frame.getContentPane().add(btnMinus);
// row three
JButton btn1 = new JButton("1");
btn1.setBackground(Color.CYAN);
btn1.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn1.setBounds(10, 174, 50, 50);
frame.getContentPane().add(btn1);
JButton btn2 = new JButton("2");
btn2.setBackground(Color.YELLOW);
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btn2.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn2.setBounds(70, 174, 50, 50);
frame.getContentPane().add(btn2);
JButton btn3 = new JButton("3");
btn3.setBackground(Color.ORANGE);
btn3.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn3.setBounds(130, 174, 50, 50);
frame.getContentPane().add(btn3);
JButton btnTimes = new JButton("x");
btnTimes.setBackground(Color.PINK);
btnTimes.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnTimes.setBounds(190, 174, 50, 50);
frame.getContentPane().add(btnTimes);
// row four
JButton btn0 = new JButton("0");
btn0.setBackground(Color.CYAN);
btn0.setFont(new Font("Tahoma", Font.PLAIN, 18));
btn0.setBounds(10, 234, 50, 50);
frame.getContentPane().add(btn0);
JButton btndot = new JButton(".");
btndot.setBackground(Color.YELLOW);
btndot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btndot.setFont(new Font("Tahoma", Font.PLAIN, 18));
btndot.setBounds(70, 234, 50, 50);
frame.getContentPane().add(btndot);
JButton btnPM = new JButton("±");
btnPM.setBackground(Color.ORANGE);
btnPM.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnPM.setBounds(130, 234, 50, 50);
frame.getContentPane().add(btnPM);
JButton btnEquals = new JButton("x");
btnEquals.setBackground(Color.PINK);
btnEquals.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnEquals.setBounds(190, 234, 50, 50);
frame.getContentPane().add(btnEquals);
}
}
txtDisplay has not been initialized anywhere in the given code.
You might be referring to your textField object though?
JButton btn7 = new JButton("7");
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// String EnterNumber = txtDisplay.getText() + btn7.getText();
// txtDisplay.setText(EnterNumber);
textField.setText(textField.getText() + btn7.getText());
}
});
I commented out the code where you use your txtDisplay object.
Keep in mind that every time you press the "7" Button, 7 will be written in the textField.

Using Metric equation for calculating BMI, how to convert imperial measurement using GUI in Java

I am new to Java and have to create a BMI calculator which allows the user to input metric or imperial measurements and calculate the BMI using one of the equations for calculating BMI. I have used the metric calculation and I have the metric measurements displaying correctly. I now need to convert the Imperial measurements into metric and then using the already existing metric BMI calculation, display the answer. I'd really appreciate if someone could help.
Here is what I have so far:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import java.awt.Font;
public class BMIFrame extends JFrame{
// Create instructions label
private JLabel instructions = new JLabel("<html>To calculate your Body
Mass Index (BMI), please "
+ "enter your weight and height in the fields provided in either
Imperial or Metric measurements.</html>");
// Metric section labels and fields
private JLabel metricHeading = new JLabel("Metric");
private JLabel metricWeight = new JLabel("Enter your Weight:");
private JTextField metTextWeight = new JTextField("0");
private JLabel weightKg = new JLabel("kgs");
private JLabel metricHeight = new JLabel("Enter your Height:");
private JTextField metTextHeight = new JTextField("0");
private JLabel heightCm = new JLabel("cms");
// Imperial section labels and fields
private JLabel imperialHeading = new JLabel("Imperial");
private JLabel imperialWeight = new JLabel("Enter your Weight:");
private JTextField impTextWeight = new JTextField("0");
private JLabel weightSt = new JLabel("st");
private JTextField impTextWeight2 = new JTextField("0");
private JLabel weightLbs = new JLabel("lbs");
private JLabel imperialHeight = new JLabel("Enter your Height:");
private JTextField impTextHeight = new JTextField("0");
private JLabel heightFt = new JLabel("ft");
private JTextField impTextHeight2= new JTextField("0");
private JLabel heightIns = new JLabel("ins");
private JButton calculateButton = new JButton("Calculate BMI");
private JButton clearButton = new JButton("Clear");
private JButton quitButton = new JButton("Quit");
private JLabel bmiInfoHeading = new JLabel("BMI Values");
private JLabel bmiInfoUnder = new JLabel("Below 18.5 = Underweight");
private JLabel bmiInfoNormal = new JLabel("18.5 - 24.9 = Normal");
private JLabel bmiInfoOver = new JLabel("25.0 - 29.9 = Overweight");
private JLabel bmiInfoObese = new JLabel("30.0 + = Obese");
// create a this is your result label
private JLabel bmiResult = new JLabel("Your BMI is ");
private JTextField resultField = new JTextField("0");
public BMIFrame() {
setLayout(null);
// Add instructions
instructions.setBounds(5, 5, 475, 38);
instructions.setBackground(getBackground());
instructions.setFont(new Font("Arial", Font.PLAIN, 13));
add(instructions);
// Add Metric heading
metricHeading.setBounds(90, -25, 225, 200);
metricHeading.setFont(new Font("Arial", Font.BOLD, 14));
add(metricHeading);
// Add Metric Weight Label
metricWeight.setBounds(5, 5, 225, 200);
metricWeight.setFont(new Font("Arial", Font.PLAIN, 13));
add(metricWeight);
// Add Metric Weight input field
metTextWeight.setBounds(120, 92, 50, 25);
metTextWeight.setHorizontalAlignment(SwingConstants.RIGHT);
add(metTextWeight);
// Add Kilogram label to weight field
weightKg.setBounds(172, 5, 225, 200);
weightKg.setFont(new Font("Arial", Font.PLAIN, 13));
add(weightKg);
// Add Metric Height Label
metricHeight.setBounds(5, 40, 225, 200);
metricHeight.setFont(new Font("Arial", Font.PLAIN, 13));
add(metricHeight);
// Add Metric Height input field
metTextHeight.setBounds(120, 127, 50, 25);
metTextHeight.setHorizontalAlignment(SwingConstants.RIGHT);
add(metTextHeight);
// Add Centimetres label to weight field
heightCm.setBounds(172, 40, 225, 200);
heightCm.setFont(new Font("Arial", Font.PLAIN, 13));
add(heightCm);
// Add imperial measurements fields
imperialHeading.setBounds(330, -25, 225, 200);
imperialHeading.setFont(new Font("Arial", Font.BOLD, 14));
add(imperialHeading);
// Add Imperial Weight Label
imperialWeight.setBounds(225, 5, 225, 200);
imperialWeight.setFont(new Font("Arial", Font.PLAIN, 13));
add(imperialWeight);
// Add Imperial Weight input field
impTextWeight.setBounds(335, 92, 50, 25);
impTextWeight.setHorizontalAlignment(SwingConstants.RIGHT);
add(impTextWeight);
// Add Stone label to weight field
weightSt.setBounds(385, 5, 225, 200);
weightSt.setFont(new Font("Arial", Font.PLAIN, 13));
add(weightSt);
// Add second Imperial Weight input field
impTextWeight2.setBounds(400, 92, 50, 25);
impTextWeight2.setHorizontalAlignment(SwingConstants.RIGHT);
add(impTextWeight2);
// Add Pounds label to weight field
weightLbs.setBounds(451, 5, 225, 200);
weightLbs.setFont(new Font("Arial", Font.PLAIN, 13));
add(weightLbs);
// Add Imperial Height Label
imperialHeight.setBounds(225, 40, 225, 200);
imperialHeight.setFont(new Font("Arial", Font.PLAIN, 13));
add(imperialHeight);
// Add Imperial Height input field
impTextHeight.setBounds(335, 127, 50, 25);
impTextHeight.setHorizontalAlignment(SwingConstants.RIGHT);
add(impTextHeight);
// Add Feet label to weight field
heightFt.setBounds(386, 40, 225, 200);
heightFt.setFont(new Font("Arial", Font.PLAIN, 13));
add(heightFt);
// Add Imperial Height input field
impTextHeight2.setBounds(400, 127, 50, 25);
impTextHeight2.setHorizontalAlignment(SwingConstants.RIGHT);
add(impTextHeight2);
// Add Inches label to height field
heightIns.setBounds(451, 40, 225, 200);
heightIns.setFont(new Font("Arial", Font.PLAIN, 13));
add(heightIns);
// Add Calculate button
calculateButton.setBounds(175, 175, 125, 50);
add(calculateButton);
// Add Clear button
clearButton.setBounds(120, 360, 115, 30);
add(clearButton);
// Add Quit button
quitButton.setBounds(240, 360, 115, 30);
add(quitButton);
// Result label
bmiResult.setBounds(10, 240, 80, 50);
add(bmiResult);
// Add result field
resultField.setBounds(86, 243, 80, 40);
resultField.setHorizontalAlignment(SwingConstants.CENTER);
resultField.setEditable(false);
add(resultField);
// BMI values display
bmiInfoHeading.setBounds(345, 230, 80, 50);
add(bmiInfoHeading);
bmiInfoUnder.setBounds(300, 255, 200, 50);
bmiInfoUnder.setFont(new Font("Arial", Font.PLAIN, 13));
add(bmiInfoUnder);
bmiInfoNormal.setBounds(300, 275, 200, 50);
bmiInfoNormal.setFont(new Font("Arial", Font.PLAIN, 13));
add(bmiInfoNormal);
bmiInfoOver.setBounds(300, 295, 200, 50);
bmiInfoOver.setFont(new Font("Arial", Font.PLAIN, 13));
add(bmiInfoOver);
bmiInfoObese.setBounds(300, 315, 200, 50);
bmiInfoObese.setFont(new Font("Arial", Font.PLAIN, 13));
add(bmiInfoObese);
ButtonHandler bh = new ButtonHandler();
calculateButton.addActionListener(bh);
clearButton.addActionListener(bh);
quitButton.addActionListener(bh);
} // end of constructor
// private inner class ButtonHandler
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
if (event.getSource() == quitButton)
System.exit(0);
else if (event.getSource() == clearButton) {
metTextWeight.setText("0");
metTextHeight.setText("0");
impTextWeight.setText("0");
impTextWeight2.setText("0");
impTextHeight.setText("0");
impTextHeight2.setText("0");
resultField.setText("0");
return;
}
try {
double metW1 = Double.parseDouble(metTextWeight.getText());
double metH1 = Double.parseDouble(metTextHeight.getText());
double impW1 = Double.parseDouble(impTextWeight.getText());
double impW2 = Double.parseDouble(impTextWeight2.getText());
double impH1 = Double.parseDouble(impTextHeight.getText());
double impH2 = Double.parseDouble(impTextHeight2.getText());
double result = 0;
if (event.getSource() == calculateButton)
result = (metW1 / (metH1 * metH1) * 10000);
String answers = String.format("%.1f", result);
resultField.setText(answers);
} // end of try method
catch(Exception ex) {
JOptionPane.showMessageDialog(BMIFrame.this, ex.toString()
, "Error Message", JOptionPane.WARNING_MESSAGE);
} // end of catch method
} // end of method actionPerformed
} // end of inner class ButtonHandler
} //end of class BMIFrame
I would suggest a different approach which should help to simplify the code. Consider this interface:
public interface BMICalculator {
public double calculate(double height, double weight);
}
And two implementations:
public class MetricBMICalculator implements BMICalculator {
public double calculate(double heightCentimeters, double weightKilograms) {
// convert as needed, calculate, and return...
}
}
public class ImperialBMICalculator implements BMICalculator {
public double calculate(double heightFeet, double weightPounds) {
// convert as needed, calculate, and return...
}
}
And within the UI have a units toggle to switch between metric and imperial. This leads to needing only one weight entry field and only one height entry field. When the toggle is triggered the text of the related labels are changed, and which implementation of the above interface is changed.
Just add before the actual calculation:
metH1 = impH1*30,48;
metH1 += impH2*2,54;
metW1 = impW1*6,35;
metW1 += impW2*0,45;

Java GUI button wont initialize

So i'm creating a program that sort of acts like a calculator for a certain item for sales. I have a calculate button but pressing the button won't initialize the code within it. I am using Swing designer for the gui. Here's the code with the button
JButton btnNewButton = new JButton("Calculate Total");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 43));
btnNewButton.setBounds(37, 1113, 330, 77);
frame.getContentPane().add(btnNewButton);
if(btnNewButton.getModel().isPressed())
{
// Sets value for # of gloves per type
LA = Integer.parseInt(textField_1.getText());
LB = Integer.parseInt(textField_8.getText());
SA = Integer.parseInt(textField_12.getText());
SB = Integer.parseInt(textField_13.getText());
total = LA + LB + SA + SB;
// Sets value for percentage of gloves compared to total
percLA = LA / total;
percLB = LB / total;
percSA = SA / total;
percSB = SB / total;
double percTotal = percLA + percLB + percSA + percSB;
//21;
// Sets value for total # of gloves
textField_22.setText(Double.toString(total));
// Sets value for percentage
textField_2.setText(Double.toString(percLA));
textField_7.setText(Double.toString(percLB));
textField_14.setText(Double.toString(percSA));
textField_15.setText(Double.toString(percSB));
textField_21.setText(Double.toString(percTotal));
// Sets value for cost per pair
costLA = Integer.parseInt(textField_3.getText());
costLB = Integer.parseInt(textField_6.getText());
costSA = Integer.parseInt(textField_16.getText());
costSB = Integer.parseInt(textField_17.getText());
}
And here's the full code if needed
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.Box;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JButton;
public class Program {
private JFrame frame;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
private JTextField textField_8;
private JTextField textField_12;
private JTextField textField_13;
private JTextField textField_14;
private JTextField textField_15;
private JTextField textField_16;
private JTextField textField_17;
private JTextField textField_18;
private JTextField textField_19;
private JTextField textField_20;
private JTextField textField_21;
private JTextField textField_22;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Program window = new Program();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Program() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1109, 1400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
// Total # of pairs per glove
double LA = 0;
double LB = 0;
double SA = 0;
double SB = 0;
double total = 0;
// Percentage of gloves compared to total
double percLA = 0;
double percLB = 0;
double percSA = 0;
double percSB = 0;
// Cost per glove type
double costLA = 0;
double costLB = 0;
double costSA = 0;
double costSB = 0;
textField_1 = new JTextField();
textField_1.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_1.setColumns(10);
textField_1.setBounds(231, 74, 200, 64);
frame.getContentPane().add(textField_1);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_2.setColumns(10);
textField_2.setBounds(440, 74, 200, 64);
frame.getContentPane().add(textField_2);
textField_3 = new JTextField();
textField_3.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_3.setColumns(10);
textField_3.setBounds(650, 74, 200, 64);
frame.getContentPane().add(textField_3);
textField_4 = new JTextField();
textField_4.setEditable(false);
textField_4.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_4.setColumns(10);
textField_4.setBounds(860, 74, 200, 64);
frame.getContentPane().add(textField_4);
textField_5 = new JTextField();
textField_5.setEditable(false);
textField_5.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_5.setColumns(10);
textField_5.setBounds(860, 147, 200, 64);
frame.getContentPane().add(textField_5);
textField_6 = new JTextField();
textField_6.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_6.setColumns(10);
textField_6.setBounds(650, 147, 200, 64);
frame.getContentPane().add(textField_6);
textField_7 = new JTextField();
textField_7.setEditable(false);
textField_7.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_7.setColumns(10);
textField_7.setBounds(440, 147, 200, 64);
frame.getContentPane().add(textField_7);
textField_8 = new JTextField();
textField_8.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_8.setColumns(10);
textField_8.setBounds(231, 147, 200, 64);
frame.getContentPane().add(textField_8);
textField_12 = new JTextField();
textField_12.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_12.setColumns(10);
textField_12.setBounds(231, 219, 200, 64);
frame.getContentPane().add(textField_12);
textField_13 = new JTextField();
textField_13.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_13.setColumns(10);
textField_13.setBounds(231, 293, 200, 64);
frame.getContentPane().add(textField_13);
textField_14 = new JTextField();
textField_14.setEditable(false);
textField_14.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_14.setColumns(10);
textField_14.setBounds(440, 219, 200, 64);
frame.getContentPane().add(textField_14);
textField_15 = new JTextField();
textField_15.setEditable(false);
textField_15.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_15.setColumns(10);
textField_15.setBounds(440, 293, 200, 64);
frame.getContentPane().add(textField_15);
textField_16 = new JTextField();
textField_16.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_16.setColumns(10);
textField_16.setBounds(650, 219, 200, 64);
frame.getContentPane().add(textField_16);
textField_17 = new JTextField();
textField_17.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_17.setColumns(10);
textField_17.setBounds(650, 293, 200, 64);
frame.getContentPane().add(textField_17);
textField_18 = new JTextField();
textField_18.setEditable(false);
textField_18.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_18.setColumns(10);
textField_18.setBounds(860, 219, 200, 64);
frame.getContentPane().add(textField_18);
textField_19 = new JTextField();
textField_19.setEditable(false);
textField_19.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_19.setColumns(10);
textField_19.setBounds(860, 293, 200, 64);
frame.getContentPane().add(textField_19);
textField_20 = new JTextField();
textField_20.setEditable(false);
textField_20.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_20.setColumns(10);
textField_20.setBounds(860, 386, 200, 64);
frame.getContentPane().add(textField_20);
textField_21 = new JTextField();
textField_21.setEditable(false);
textField_21.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_21.setColumns(10);
textField_21.setBounds(440, 386, 200, 64);
frame.getContentPane().add(textField_21);
textField_22 = new JTextField();
textField_22.setEditable(false);
textField_22.setFont(new Font("Tahoma", Font.PLAIN, 40));
textField_22.setColumns(10);
textField_22.setBounds(231, 386, 200, 64);
frame.getContentPane().add(textField_22);
Box horizontalBox = Box.createHorizontalBox();
horizontalBox.setBounds(213, 74, -187, 64);
frame.getContentPane().add(horizontalBox);
Box horizontalBox_1 = Box.createHorizontalBox();
horizontalBox_1.setBounds(22, 74, 200, 64);
frame.getContentPane().add(horizontalBox_1);
JLabel lblTest = new JLabel("Latex A");
lblTest.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_1.add(lblTest);
Box horizontalBox_2 = Box.createHorizontalBox();
horizontalBox_2.setBounds(22, 147, 200, 64);
frame.getContentPane().add(horizontalBox_2);
JLabel lblLatexB = new JLabel("Latex B");
lblLatexB.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_2.add(lblLatexB);
Box horizontalBox_3 = Box.createHorizontalBox();
horizontalBox_3.setBounds(22, 219, 200, 64);
frame.getContentPane().add(horizontalBox_3);
JLabel lblSyntheticA = new JLabel("Synthetic A");
lblSyntheticA.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_3.add(lblSyntheticA);
Box horizontalBox_4 = Box.createHorizontalBox();
horizontalBox_4.setBounds(22, 293, 200, 64);
frame.getContentPane().add(horizontalBox_4);
JLabel lblSyntheticB = new JLabel("Synthetic B");
lblSyntheticB.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_4.add(lblSyntheticB);
Box horizontalBox_5 = Box.createHorizontalBox();
horizontalBox_5.setBounds(231, 0, 200, 64);
frame.getContentPane().add(horizontalBox_5);
JLabel lblPairsYear = new JLabel("Pairs / Year");
lblPairsYear.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_5.add(lblPairsYear);
Box horizontalBox_6 = Box.createHorizontalBox();
horizontalBox_6.setBounds(440, 0, 200, 64);
frame.getContentPane().add(horizontalBox_6);
JLabel lblOfTotal = new JLabel("% Of Total");
lblOfTotal.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_6.add(lblOfTotal);
Box horizontalBox_7 = Box.createHorizontalBox();
horizontalBox_7.setBounds(650, 0, 200, 64);
frame.getContentPane().add(horizontalBox_7);
JLabel lblPricePerPair = new JLabel("Price Per Pair");
lblPricePerPair.setFont(new Font("Tahoma", Font.PLAIN, 33));
horizontalBox_7.add(lblPricePerPair);
Box horizontalBox_8 = Box.createHorizontalBox();
horizontalBox_8.setBounds(860, 0, 200, 64);
frame.getContentPane().add(horizontalBox_8);
JLabel lblTotalSpent = new JLabel("Total Spent");
lblTotalSpent.setFont(new Font("Tahoma", Font.PLAIN, 35));
horizontalBox_8.add(lblTotalSpent);
JSlider slider = new JSlider();
slider.setToolTipText("h");
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setFont(new Font("Tahoma", Font.PLAIN, 72));
slider.setBounds(39, 592, 1021, 88);
frame.getContentPane().add(slider);
JLabel lblAverageSalePrice = new JLabel("Average Sale Price");
lblAverageSalePrice.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblAverageSalePrice.setBounds(39, 536, 384, 43);
frame.getContentPane().add(lblAverageSalePrice);
JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 43));
textArea.setBounds(468, 525, 172, 61);
frame.getContentPane().add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setFont(new Font("Monospaced", Font.PLAIN, 43));
textArea_1.setBounds(468, 714, 172, 61);
frame.getContentPane().add(textArea_1);
JLabel lblTotalNumberOf = new JLabel("Total Number Of Pairs");
lblTotalNumberOf.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblTotalNumberOf.setBounds(39, 725, 384, 43);
frame.getContentPane().add(lblTotalNumberOf);
JSlider slider_1 = new JSlider();
slider_1.setToolTipText("h");
slider_1.setPaintTicks(true);
slider_1.setPaintLabels(true);
slider_1.setFont(new Font("Tahoma", Font.PLAIN, 72));
slider_1.setBounds(39, 783, 1021, 88);
frame.getContentPane().add(slider_1);
JTextArea textArea_2 = new JTextArea();
textArea_2.setFont(new Font("Monospaced", Font.PLAIN, 43));
textArea_2.setBounds(468, 895, 172, 61);
frame.getContentPane().add(textArea_2);
JLabel lblPriceReduction = new JLabel("Price Reduction");
lblPriceReduction.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblPriceReduction.setBounds(39, 917, 384, 43);
frame.getContentPane().add(lblPriceReduction);
JSlider slider_2 = new JSlider();
slider_2.setToolTipText("h");
slider_2.setPaintTicks(true);
slider_2.setPaintLabels(true);
slider_2.setFont(new Font("Tahoma", Font.PLAIN, 72));
slider_2.setBounds(39, 968, 1021, 88);
frame.getContentPane().add(slider_2);
JTextArea textArea_3 = new JTextArea();
textArea_3.setEditable(false);
textArea_3.setFont(new Font("Monospaced", Font.PLAIN, 43));
textArea_3.setBounds(417, 1129, 292, 61);
frame.getContentPane().add(textArea_3);
JButton btnNewButton = new JButton("Calculate Total");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 43));
btnNewButton.setBounds(37, 1113, 330, 77);
frame.getContentPane().add(btnNewButton);
if(btnNewButton.getModel().isPressed())
{
// Sets value for # of gloves per type
LA = Integer.parseInt(textField_1.getText());
LB = Integer.parseInt(textField_8.getText());
SA = Integer.parseInt(textField_12.getText());
SB = Integer.parseInt(textField_13.getText());
total = LA + LB + SA + SB;
// Sets value for percentage of gloves compared to total
percLA = LA / total;
percLB = LB / total;
percSA = SA / total;
percSB = SB / total;
double percTotal = percLA + percLB + percSA + percSB;
//21;
// Sets value for total # of gloves
textField_22.setText(Double.toString(total));
// Sets value for percentage
textField_2.setText(Double.toString(percLA));
textField_7.setText(Double.toString(percLB));
textField_14.setText(Double.toString(percSA));
textField_15.setText(Double.toString(percSB));
textField_21.setText(Double.toString(percTotal));
// Sets value for cost per pair
costLA = Integer.parseInt(textField_3.getText());
costLB = Integer.parseInt(textField_6.getText());
costSA = Integer.parseInt(textField_16.getText());
costSB = Integer.parseInt(textField_17.getText());
}
}
}
Update : created an anonymous class for the listener but my code won't initialize for where I place the code for my button to perform. Here's the code
JTextArea textArea_2 = new JTextArea();
textArea_2.setFont(new Font("Monospaced", Font.PLAIN, 43));
textArea_2.setBounds(468, 895, 172, 61);
frame.getContentPane().add(textArea_2);
JLabel lblPriceReduction = new JLabel("Price Reduction");
lblPriceReduction.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblPriceReduction.setBounds(39, 917, 384, 43);
frame.getContentPane().add(lblPriceReduction);
JSlider slider_2 = new JSlider();
slider_2.setToolTipText("h");
slider_2.setPaintTicks(true);
slider_2.setPaintLabels(true);
slider_2.setFont(new Font("Tahoma", Font.PLAIN, 72));
slider_2.setBounds(39, 968, 1021, 88);
frame.getContentPane().add(slider_2);
JTextArea textArea_3 = new JTextArea();
textArea_3.setEditable(false);
textArea_3.setFont(new Font("Monospaced", Font.PLAIN, 43));
textArea_3.setBounds(417, 1129, 292, 61);
frame.getContentPane().add(textArea_3);
JButton btnNewButton = new JButton("Calculate Total");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 43));
btnNewButton.setBounds(37, 1113, 330, 77);
frame.getContentPane().add(btnNewButton);
btnNewButton.addActionListener(new Action());
}
static class Action implements ActionListener {
public void actionPerformed (ActionEvent e){
textArea_1.setText("This is a test");
}
}
}
However where I typed //Trying to place code here, I can't call for example textfield_3.setText();. Nothing will initialize.
You have to add an actionListener to the JButton and implement an actionPerformed method of that interface. Please, take a look at http://docs.oracle.com/javase/tutorial/uiswing/components/button.html and you will get some tips. Your code is just not attached to the button.
I'm not really sure what the real problem is, but I will recommend you to implement ActionListener in your class so you will have to overwrite the ActionPerformed method instead of just using an anonymous class.
This would be the example:
public class Programs implements ActionListener{
// When you create your button
JButton btnNewButton = new JButton("Calculate Total");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 43));
// This line tells the button where the actionListener will be
// handlded
btnNewButton.addActionListener(this);
//all your code...
// I will catch all the actions you send me
public void actionPerformed(ActionEvent e){
// Here goes the name of the instance, remember that.
if(e.getSource(btnNewButton)){
//code to execute when you click the button ...
}
}
}
The second option would be just adding an anonymous class, I don't recommend this is because the code can get a little dirty.
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Code to execute when clicked
}
});
in this example you don't need to implement ActionListener interface, you just make an anonymous class and internally assing a method.
Good luck, if you have any question i'll be here.

Program Terminates without running in eclipse

When I run this code ( having simple buttons and a LOGIN button with an action listener), it terminates without running and without showing screen.
I have tried System.exit(0); in main function to overcome this terminating issue but all in vain
public class HOme extends JFrame{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
Color cardinal = new Color(194, 35, 38);
int w=155;
int h=50;
public HOme(String title) {
super(title);
getContentPane().setSize(width,height);
getContentPane().setBackground(Color.WHITE);
getContentPane().setLayout(null);
final JPanel panel2 = new JPanel();
panel2.setBounds(364, 33, 664, 344);
getContentPane().add(panel2);
JPanel panel3 = new JPanel();
panel3.setBackground(Color.WHITE);
panel3.setBounds(81, 382, 947, 243);
getContentPane().add(panel3);
panel3.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnHome.setForeground(Color.WHITE);
btnHome.setBackground(cardinal);
btnHome.setBounds(517, 33, w, h);
btnHome.setContentAreaFilled(false);
btnHome.setOpaque(true);
panel3.add(btnHome);
JButton btnClients = new JButton("Clients");
btnClients.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnClients.setForeground(Color.WHITE);
btnClients.setBounds(690, 33, w, h);
btnClients.setBackground(cardinal);
btnClients.setContentAreaFilled(false);
btnClients.setOpaque(true);
panel3.add(btnClients);
JButton btnClose = new JButton("Close");
btnClose.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnClose.setForeground(Color.WHITE);
btnClose.setBounds(690, 198, w, h);
btnClose.setBackground(cardinal);
btnClose.setContentAreaFilled(false);
btnClose.setOpaque(true);
panel3.add(btnClose);
JButton btnLogin = new JButton("Admin Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login l=new Login();
panel2.add(l);
}
});
btnLogin.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnLogin.setForeground(Color.WHITE);
btnLogin.setBounds(517, 116, w, h);
btnLogin.setBackground(cardinal);
btnLogin.setContentAreaFilled(false);
btnLogin.setOpaque(true);
panel3.add(btnLogin);
JPanel panel1 = new JPanel();
panel1.setBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(204, 51, 0), null));
panel1.setBackground(Color.WHITE);
panel1.setBounds(81, 33, 263, 344);
getContentPane().add(panel1);
panel1.setLayout(null);
JButton btnStartMonitoring = new JButton("");
btnStartMonitoring.setIcon(new ImageIcon(path1));
btnStartMonitoring.setBackground(cardinal);
btnStartMonitoring.setForeground(Color.WHITE);
btnStartMonitoring.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnStartMonitoring.setBounds(10, 274, 239, 59);
panel1.add(btnStartMonitoring);
JLabel lblLogo = new JLabel("New label");
lblLogo.setIcon(new ImageIcon(path2));
lblLogo.setBounds(0, 11, 263, 253);
panel1.add(lblLogo);
}
public static void main(String args[]) {
new HOme("HOme");
//System.exit(0);
}
}
Edited
I have a login class extended from JPanel. When I click on Login Button from Home. It is not showing Login panel
Login.class
public class Login extends JPanel {
private JTextField txtPassword;
private JTextField txtID;
Color cardinal = new Color(194, 35, 38);
int w=155;
int h=50;
public Login() {
setBackground(Color.WHITE);
setLayout(null);
JLabel lblLogin = new JLabel("Login ");
lblLogin.setBackground(Color.ORANGE);
lblLogin.setHorizontalAlignment(SwingConstants.RIGHT);
lblLogin.setFont(new Font("Trajan Pro", Font.BOLD, 36));
lblLogin.setBounds(125, 0, 424, 59);
lblLogin.setBackground(cardinal);
//lblLogin.setContentAreaFilled(false);
lblLogin.setOpaque(true);
lblLogin.setForeground(Color.white);
add(lblLogin);
JLabel lblId = new JLabel("ID");
lblId.setHorizontalAlignment(SwingConstants.RIGHT);
lblId.setFont(new Font("Tekton Pro", Font.PLAIN, 23));
lblId.setBounds(181, 127, 66, 28);
add(lblId);
JLabel lblPassword = new JLabel("Password");
lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
lblPassword.setFont(new Font("Tekton Pro", Font.PLAIN, 23));
lblPassword.setBounds(136, 188, 111, 28);
add(lblPassword);
txtPassword = new JTextField();
lblPassword.setLabelFor(txtPassword);
txtPassword.setBounds(266, 183, 256, 41);
lblPassword.setForeground(cardinal);
add(txtPassword);
txtPassword.setColumns(10);
txtID = new JTextField();
lblId.setLabelFor(txtID);
txtID.setBounds(266, 123, 256, 39);
lblId.setForeground(cardinal);
add(txtID);
txtID.setColumns(10);
JButton btnLogin = new JButton("Login");
btnLogin.setForeground(Color.WHITE);
btnLogin.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnLogin.setBounds(324, 294, w, h);
btnLogin.setBackground(cardinal);
btnLogin.setContentAreaFilled(false);
btnLogin.setOpaque(true);
add(btnLogin);
setVisible(true);
}
You are not making your JFrame visible.
You can do either -
In your constructor, make it visible by adding the following line at the end -
setVisible(true);
Or in your main() function you can do -
HOme h = new HOme("HOme");
h.setVisible(true);
Answer to second part:
Import MouseListener, import java.awt.event.MouseListener;
Construct a MouseListener somewhere, include action of the button
Where you define btnLogin, add a line btnLogin.addMouseListener(<name of MouseListener>);
An example: http://www.java2s.com/Code/Java/Swing-JFC/ButtonActionSample.htm
Add something like setVisible(true); at the end of the HOme method.

Why joptionpane popup two times

I have two problem now.
My First Problem is when i click the confirm button, it will insert the data two times into ms access database.
My Second Problem is why joptionpane also popup two times.
I have the main login page when open the program.
When i click the sign up button, it will remove all the component inside the center jpanel.
Then it will add again component to use in registration form like jtextfield,jlabel,icon for username,password,tel no and others.I already checked, that the statement to execute insert statement and joptionpanes only have one times only.
This is the full code of my program
package userForm;
import java.sql.*;
import java.util.logging.Handler;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class loginForm extends JFrame implements ActionListener{
private JPanel centerPanel,bottomPanel;
private JLabel titleLabel, descriptionLabel;
private JLabel usernameLabel, passwordLabel, signInLabel, iconUsername, iconPassword;
private JLabel signUpLabel, fullNameLabel, staffIDLabel, usernameRegLabel, passwordRegLabel, telNoLabel, emailLabel;
private JLabel iconFullName, iconStaffID, iconUsernameReg, iconPasswordReg, iconTelNo, iconEmail;
private JTextField usernameField, fullNameField, staffIDField, usernameRegField, telNoField, emailField;
private JPasswordField passwordField, passwordRegField;
private JButton loginButton, signUpButton,confirmButton,exitButton;
private String username;
private String password;
userDatabase db;
userDatabase db1;
handler handle;
public loginForm(String title) {
db=new userDatabase();
handle =new handler();
//create label to use in topPanel
titleLabel = new JLabel("ABC Burger Inventory System");
titleLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 23));
titleLabel.setForeground(Color.white);
Border empty = new EmptyBorder(30, 20, 0, 0);
titleLabel.setBorder(empty);
descriptionLabel = new JLabel("Please Login To Use This System");
Border empty1 = new EmptyBorder(-30, 20, 0, 0);
descriptionLabel.setBorder(empty1);
descriptionLabel.setFont(new Font("Calibri", Font.HANGING_BASELINE, 14));
descriptionLabel.setForeground(Color.white);
//create label to use in centerPanel
signInLabel = new JLabel("SIGN IN");
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password");
//create textfield to use in center Panel
usernameField = new JTextField("Required");
passwordField = new JPasswordField("Required");
//create label to use in registration form
signUpLabel = new JLabel("SIGN UP");
fullNameLabel = new JLabel("Full Name:");
staffIDLabel = new JLabel("Staff ID:");
usernameRegLabel = new JLabel("Username:");
passwordRegLabel = new JLabel("Password");
telNoLabel = new JLabel("Tel No:");
emailLabel = new JLabel("Email:");
//create textfield to use in registration form
fullNameField = new JTextField(30);
staffIDField = new JTextField(30);
usernameRegField = new JTextField(30);
passwordRegField = new JPasswordField(30);
telNoField = new JTextField(30);
emailField = new JTextField(30);
//create button to use in bottom Panel
loginButton = new JButton("Login");
signUpButton = new JButton("Sign Up");
confirmButton = new JButton("Confirm");
confirmButton.addActionListener(this);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
//create panel to use in frame
topPanelWithBackground topPanel = new topPanelWithBackground();
topPanel.setLayout(new GridLayout(2,1));
centerPanel = new JPanel();
centerPanel.setLayout(null);
bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 10));
//add component to top panel
topPanel.add(titleLabel);
topPanel.add(descriptionLabel);
//add component to center panel
signInLabel.setBounds(270, 30, 100, 20);
signInLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20));
centerPanel.add(signInLabel);
usernameLabel.setBounds(200, 60, 100, 20);
usernameLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameLabel);
ImageIcon imageUser = new ImageIcon("user.png");
iconUsername = new JLabel(imageUser, JLabel.CENTER);
iconUsername.setBounds(160, 90, 32, 32);
centerPanel.add(iconUsername);
usernameField.setBounds(200, 90, 200, 32);
usernameField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameField);
passwordLabel.setBounds(200, 140, 100, 20);
passwordLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordLabel);
ImageIcon imagePassword = new ImageIcon("password.png");
iconUsername = new JLabel(imagePassword, JLabel.CENTER);
iconUsername.setBounds(160, 170, 32, 32);
centerPanel.add(iconUsername);
passwordField.setBounds(200, 170, 200, 32);
passwordField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordField);
loginButton.setFont(new Font("Calibri", Font.BOLD, 14));
loginButton.addActionListener(handle);
bottomPanel.add(loginButton);
signUpButton.setFont(new Font("Calibri", Font.BOLD, 14));
signUpButton.addActionListener(this);
bottomPanel.add(signUpButton);
//add confirm button
exitButton.setFont(new Font("Calibri", Font.BOLD, 14));
exitButton.addActionListener(this);
bottomPanel.add(exitButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topPanel, BorderLayout.NORTH );
getContentPane().add(centerPanel, BorderLayout.CENTER);
getContentPane().add(bottomPanel, BorderLayout.SOUTH);
//frame behaviour
super.setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit
setSize(600,500);
}
class handler implements ActionListener{
public void actionPerformed(ActionEvent as) {
if(as.getSource()==loginButton){
centerPanel.removeAll();
centerPanel.revalidate();
centerPanel.repaint();
//add component to center panel
signInLabel.setBounds(270, 30, 100, 20);
signInLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20));
centerPanel.add(signInLabel);
usernameLabel.setBounds(200, 60, 100, 20);
usernameLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameLabel);
ImageIcon imageUser = new ImageIcon("user.png");
iconUsername = new JLabel(imageUser, JLabel.CENTER);
iconUsername.setBounds(160, 90, 32, 32);
centerPanel.add(iconUsername);
usernameField.setBounds(200, 90, 200, 32);
usernameField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameField);
passwordLabel.setBounds(200, 140, 100, 20);
passwordLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordLabel);
ImageIcon imagePassword = new ImageIcon("password.png");
iconUsername = new JLabel(imagePassword, JLabel.CENTER);
iconUsername.setBounds(160, 170, 32, 32);
centerPanel.add(iconUsername);
passwordField.setBounds(200, 170, 200, 32);
passwordField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordField);
char[] temp_pwd=passwordField.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd);
System.out.println("Username,Pwd:"+usernameField.getText()+","+pwd);
//The entered username and password are sent via "checkLogin()" which return boolean
if(db.checkLogin(usernameField.getText(), pwd))
{
newFrame regFace =new newFrame();
regFace.setVisible(true);
dispose();
}
else if(usernameField.getText().equals("") || passwordField.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please fill out the form","Error!!",
JOptionPane.ERROR_MESSAGE);
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==signUpButton){
centerPanel.removeAll();
//sign up label
signUpLabel.setBounds(270, 30, 100, 20);
signUpLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20));
centerPanel.add(signUpLabel);
//fullname label,icon and field
fullNameLabel.setBounds(80, 60, 100, 20);
fullNameLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(fullNameLabel);
ImageIcon imageFullname = new ImageIcon("fullname.png");
iconUsernameReg = new JLabel(imageFullname, JLabel.CENTER);
iconUsernameReg.setBounds(40, 90, 32, 32);
centerPanel.add(iconUsernameReg);
fullNameField.setBounds(80, 90, 200, 32);
fullNameField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(fullNameField);
//staffID label,icon and field
staffIDLabel.setBounds(80, 140, 100, 20);
staffIDLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(staffIDLabel);
ImageIcon imageStaffID = new ImageIcon("staffID.png");
iconStaffID = new JLabel(imageStaffID, JLabel.CENTER);
iconStaffID.setBounds(40, 170, 32, 32);
centerPanel.add(iconStaffID);
staffIDField.setBounds(80, 170, 200, 32);
staffIDField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(staffIDField);
//usernameReg label,icon and field
usernameRegLabel.setBounds(80, 220, 100, 20);
usernameRegLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameRegLabel);
ImageIcon imageUsernameReg = new ImageIcon("user.png");
iconUsernameReg = new JLabel(imageUsernameReg, JLabel.CENTER);
iconUsernameReg.setBounds(40, 250, 32, 32);
centerPanel.add(iconUsernameReg);
usernameRegField.setBounds(80, 250, 200, 32);
usernameRegField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameRegField);
//passwordReg label,icon and field
passwordRegLabel.setBounds(350, 60, 100, 20);
passwordRegLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordRegLabel);
ImageIcon imagePasswordReg = new ImageIcon("password.png");
iconPasswordReg = new JLabel(imagePasswordReg, JLabel.CENTER);
iconPasswordReg.setBounds(310, 90, 32, 32);
centerPanel.add(iconPasswordReg);
passwordRegField.setBounds(350, 90, 200, 32);
passwordRegField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordRegField);
//telNo label,icon and field
telNoLabel.setBounds(350, 140, 100, 20);
telNoLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(telNoLabel);
ImageIcon imagetelNo = new ImageIcon("phone.png");
iconTelNo = new JLabel(imagetelNo, JLabel.CENTER);
iconTelNo.setBounds(310, 170, 32, 32);
centerPanel.add(iconTelNo);
telNoField.setBounds(350, 170, 200, 32);
telNoField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(telNoField);
//Email label,icon and field
emailLabel.setBounds(350, 220, 100, 20);
emailLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(emailLabel);
ImageIcon imageEmail = new ImageIcon("mail.png");
iconEmail = new JLabel(imageEmail , JLabel.CENTER);
iconEmail .setBounds(310, 250, 32, 32);
centerPanel.add(iconEmail );
emailField.setBounds(350, 250, 200, 32);
emailField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(emailField);
//add confirm button
confirmButton.setFont(new Font("Calibri", Font.BOLD, 14));
confirmButton.addActionListener(this);
bottomPanel.add(confirmButton);
centerPanel.revalidate();
centerPanel.repaint();
}
else if(ae.getSource()==confirmButton){
char[] temp_pwd1=passwordRegField.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd1);
if(fullNameField.getText().equals("") || staffIDField.getText().equals("") || usernameRegField.getText().equals("") || passwordRegField.getPassword().length == 0 || telNoField.getText().equals("") || emailField.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please Fill Out Any Field", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
db1 = new userDatabase();
try {
db1.insertData(fullNameField.getText(), staffIDField.getText(), usernameRegField.getText(), pwd, telNoField.getText(), emailField.getText());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else if(ae.getSource()==exitButton){
System.exit(0);
}
}
}
When you click the sign up button you are adding listener to the confirm button again. So when you click the confirm button it is executed twice.
Remove the following line in the actionPerformed method of LoginForm
confirmButton.addActionListener(this);

Categories