Make JButton insert text from JTextField into variables? - java

I'm trying to write a program that will take text in a JTextField and put it into variables I've declared when I press a JButton. I need to calculate weekly pay for a school project, but that only requires the console, I'm doing the GUI for my own fun. I'm trying to get it so when I hit 'calc' it'll take the imputs from id, rh, oh, hp, etc and calculate weekly pay (wp), which will then be printed on the right column next to the calc button.
//the calculations aren't complete yet until I finish the GUI
public class Weekly_Pay
{
public static void calculations(String[] args)
{
Scanner imput = new Scanner(System.in);
System.out.println("ID number: ");
int employeeId = imput.nextInt();
System.out.println("Hourly Wage: ");
Double hourlyWage = imput.nextDouble();
System.out.println("Regular Hours: ");
double regularHours = imput.nextDouble();
System.out.println("Overtime Hours: ");
double overtimeHours = imput.nextDouble();
double overtimePay = round(overtimeHours * (1.5 * hourlyWage));
double regularPay = round(hourlyWage * regularHours);
double weeklyPay = regularPay + overtimePay;
System.out.println("Employee ID Number:" + employeeId);
System.out.printf("Weekly Pay: " + "$%.2f\n", weeklyPay);
}
public static double round(double num)
{
// rounding to two decimal places
num *= 100;
int rounded = (int) Math.round(num);
return rounded/100.0;
}
public static void main(String[] args)
{
JFrame window = new JFrame();
window.setTitle("Weekly Pay");
window.setSize(350, 200);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Color lGray = new Color(209, 209, 209);
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setBackground(lGray);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
JTextField idEntry = new JTextField(); //where the user imputs their ID
JTextField hwEntry = new JTextField(); //where the user imputs their hourly wage
JTextField rhEntry = new JTextField(); //where the user imputs their regular hours
JTextField ohEntry = new JTextField(); //where the user imputs their overtime hours
JLabel id = new JLabel("ID Number");
JLabel hw = new JLabel("Hourly Wage");
JLabel rh = new JLabel("Regular Hours");
JLabel oh = new JLabel("Overtime Hours");
JButton calc = new JButton("Calculate");
JLabel wp = new JLabel(" Weekly Pay: $" + "$%.2f\n", weeklyPay);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().
addComponent(id).addComponent(hw).addComponent(rh).addComponent(oh).addComponent(calc));
hGroup.addGroup(layout.createParallelGroup().
addComponent(idEntry).addComponent(hwEntry).addComponent(rhEntry).addComponent(ohEntry).addComponent(wp));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(id).addComponent(idEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(hw).addComponent(hwEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(rh).addComponent(rhEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(oh).addComponent(ohEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(calc).addComponent(wp));
layout.setVerticalGroup(vGroup);
window.add(panel);
window.setVisible(true);
}
}

for example:
String input = new String();
JButton mbutt = new JButton;
JTextField jtxt = new JTextField();
mbutt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
input = jtxt.getText().toString();
}
});
////////////////////////////////// Edited Part //////////////////////////////
Now few things before i jump into the code.
- I just wanted to show the working of ActionListener, and how to extract a data from a field and put it into a variable.
- Its a bad practice to directly put the component on the JFrame, and thats exactly what i have done here (too bad of me..!!!), so You should always use something like a JPanel over the JFrame, and then place the component over it. In order to keep it Simple i have Deliberately use direct JFrame to hold the components.
- And yes, Its always a very good practice to have the UI work on the UI thread, and Non-UI work on Non-UI thread.
- In Swings main() method is Not long lived, after scheduling the construction of GUI in the Event Dispatcher Thread it exits... So now its the responsibility of EDT to handle the GUI, so you should keep the EDT for handling the GUI only, as i have done it in the main() method [EventQueue.invokeLater()].
Full Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Tes extends JFrame {
String input;
JTextField jtxt;
JButton mbutt;
public Tes(){
//--ALWAYS USE A JPANEL OVER JFRAME, I DID THIS TO KEEP IT SIMPLE FOR U--//
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setComponent();
this.setHandler();
}
public void setComponent(){
jtxt = new JTextField("Hello");
mbutt = new JButton("Button");
this.add(BorderLayout.SOUTH,mbutt);
this.add(BorderLayout.NORTH,jtxt);
}
public void setHandler(){
mbutt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
input = jtxt.getText().toString();
System.out.println("Input Value: "+input);
**//--See your Console Output everytime u press the button--//**
}
});
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
#Override
public void run() {
Tes t = new Tes();
t.setVisible(true);
}
});
}
}

Related

Is there a way to call a method from a separate class in a Java GUI?

I am working on a project for a class. The project asked me to create 3 classes, one parent and two children, with 3 methods in each. It then asked me to create a GUI that would calculate the sales tax based on a few fields, including text and radio buttons. In my head, I would call my methods to run if a certain radio button is clicked, ie if the Hybrid button is clicked, it'll run the toString from the Hybrid class. Can someone help me figure out how exactly to do this?
package projecttwo;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.scene.control.ToggleGroup;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import projectTwo.Automobile;
import projectTwo.Electric;
import projectTwo.Hybrid;
/**
* CMIS242
* November 14, 2020
* Sabrina Riley
* This program computes the sales tax for a collection of automobiles
*/
public class ProjectTwo extends JFrame implements ActionListener {
/**
* #param args the command line arguments
*/
//Variable declaration
private String select;
private JFrame frame;
private JPanel panel;
private JLabel label, label2, label3, label4, label5;
private JFormattedTextField mmText, salesText, mpgText, weightText, compute;
private JButton button, button2, button3;
private JRadioButton hybrid, electric, other;
private ButtonGroup bg;
private JPanel radioPanel;
Automobile car = new Automobile();
public ProjectTwo() {
//initialize GUI
frame = new JFrame();
//HandlerClass handler = new HandlerClass();
//add compute sales tax button
button = new JButton("Compute Sales Tax");
button.setBounds(0,100,150,50);
add(button);
button.addActionListener(this);
//add display results button
button2 = new JButton("Display Results");
button2.setBounds(0,200, 150, 50);
button2.addActionListener(this);
//add clear fields button
button3 = new JButton("Clear Fields");
button3.setBounds(200,200, 150, 50);
button3.addActionListener(this);
//add text field to display results from compute sales button
compute = new JFormattedTextField();
compute.setBounds(200,100,150,50);
compute.setEditable(false);
//add all other text fields
mmText = new JFormattedTextField();
mmText.addKeyListener(null);
//mmText.addActionListener(this);
salesText = new JFormattedTextField();
mpgText = new JFormattedTextField();
weightText = new JFormattedTextField();
//add radio buttons to pick between hybrid, electric, and other
hybrid = new JRadioButton("Hybrid", true);
electric = new JRadioButton("Electric", false);
other = new JRadioButton("Other", false);
//group the radio buttons together
bg = new ButtonGroup();
bg.add(hybrid);
bg.add(electric);
bg.add(other);
//arrange buttons vertically
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(3,1));
//radioPanel.setBounds(100,200,150,200);
radioPanel.add(hybrid);
radioPanel.add(electric);
radioPanel.add(other);
setContentPane(radioPanel);
pack();
//make them listen to clicks
hybrid.addActionListener(this);
electric.addActionListener(this);
other.addActionListener(this);
//label all text fields
label = new JLabel("Make and Model");
label.setBounds(0, 0, 100, 150);
label2 = new JLabel("Sales Price");
label3 = new JLabel("Automobile Type");
label4 = new JLabel("Miles Per Gallon");
label5 = new JLabel("Weight in Pounds");
//implement panel with all labels, text fields, buttons, and radio buttons
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
//panel.setLayout(GridLayout(0,2));
panel.setLayout(new GridLayout(0,2));
panel.setSize(500, 500);
panel.add(label);
panel.add(mmText);
panel.add(label2);
panel.add(salesText);
panel.add(hybrid);
panel.add(electric);
panel.add(other);
panel.add(label3);
panel.add(mpgText);
panel.add(label4);
panel.add(weightText);
panel.add(label5);
panel.add(button);
panel.add(compute);
panel.add(button2);
panel.add(button3);
panel.add(radioPanel);
//set frame dimensions
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Automobile Sales Tax Calculator");
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String user = mmText.getText();
String sales = salesText.getText();
String mpg = mpgText.getText();
String weight = weightText.getText();
this.clearFields();
e.getActionCommand();
if(e.getSource()==hybrid) {
System.out.println("car is a hybrid");
} else if (e.getSource()==electric){
System.out.println("car is electric");
} else
System.out.println("car is basic");
System.out.println(", " + user + sales + ", " + weight + ", " + mpg);
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void clearFields() {
mmText.setText(null);
salesText.setText(null);
mpgText.setText(null);
weightText.setText(null);
compute.setText(null);
hybrid.setSelected(false);
electric.setSelected(false);
other.setSelected(false);
}
public static void main(String[] args) {
// TODO code application logic here
new ProjectTwo();
}
}
package projectTwo;
/**
* CMIS242
* November 14, 2020
* Sabrina Riley
* This program computes the sales tax for a collection of automobiles
*/
public class Automobile {
protected String make;
protected String model;
protected double salesPrice;
protected double salesTax;
public Automobile() {
make = "brand";
model = "type";
}
//A constructor that allows the make and purchase price to be initialized
public Automobile(String make, String model, double salesPrice, double salesTax) {
this.make = make;
this.model = model;
this.salesPrice = salesPrice;
this.salesTax = salesTax;
}
//A method that returns the base sales tax computed as 5% of the sales price
public double salesTax() {
salesTax = salesPrice * 0.05;
return salesTax;
}
//A toString method that returns a string containing the make and model of the
//automobile, the sales price, and the sales tax
public String toString() {
return make + model + salesTax;
}
}
package projectTwo;
/**
* CMIS242
* November 14, 2020
* Sabrina Riley
* This program computes the sales tax for a collection of automobiles
*/
public class Hybrid extends Automobile {
protected int mpg;
protected double discount;
//A constructor that allows the make and purchase price to be initialized
public Hybrid(int mpg) {
super();
mpg = 0;
}
public Hybrid(String make, String model, double salesPrice, double salesTax, int mpg) {
super(make, model, salesPrice, salesTax);
this.mpg = mpg;
}
//A method that returns the base sales tax computed as 5% of the sales price
#Override
public double salesTax() {
if (mpg < 40)
discount = salesTax + 100;
else
discount = salesTax + 100 + (mpg * 2);
return discount;
}
//A toString method that returns a string containing the make and model of the
//automobile, the sales price, and the sales tax
#Override
public String toString() {
return make + model + salesPrice + discount + discount;
}
}
In my humble opinion, if understand correctly what you want to achieve, you have to create an instance of the "Hybrid" class in ProjectTwo's constructor, just like:
Declare the variable there you have all variable declarations, just to have it global:
private Hybrid hybr;
Create the instance in constructor:
hybr = new Hybrid("make", "hybrid's model", 20500.50, 12.5, 5);
And then in your code, there where you need to use to Hybrid's methods you call you method, in this case hybr.toString().

How do I get my Java GUI to calculate fields properly?

I am not running into any errors but nothing happens when I run the program. Any help would be appreciated. I just need to be able to add a starting balance and then calculate a deposit or withdraw.
package account;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class GUI implements ActionListener{
JTextField txt, txt2, txt3;
JButton submit;
JLabel balance;
double Balance = 0.00;
GUI(){
JFrame main = new JFrame("Account GUI ");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt = new JTextField(10);
txt2 = new JTextField(10);
txt3 = new JTextField(10);
JPanel gui = new JPanel(new BorderLayout(8,8));
gui.setBorder(new EmptyBorder(8,8,8,8));
main.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Starting Balance"));
controls.add(txt);
txt.addActionListener(this);
labels.add(new JLabel("Deposit Amount: "));
controls.add(txt2);
txt2.addActionListener(this);
labels.add(new JLabel("Withdraw Amount: "));
controls.add(txt3);
txt3.addActionListener(this);
submit = new JButton("Submit");
gui.add(submit, BorderLayout.SOUTH);
balance = new JLabel("New Balance " + Balance);
gui.add(balance,BorderLayout.NORTH);
submit.addActionListener(this);
main.pack();
main.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
if (txt!=null){
double strtblnc = Double.parseDouble(txt.getText());
Balance = Balance + strtblnc;
}
else if (txt2!=null){
double dpst = Double.parseDouble(txt2.getText());
Balance = Balance + dpst;
}
else if(txt3!=null){
double wthdrw = Double.parseDouble(txt3.getText());
Balance = Balance - wthdrw;
}
}
public static void main(String[] args) {
GUI test = new GUI();
}
}
The reason why you are not receiving a new balance number is because you are never actually resetting the text to your JLabel. When you originally initialized:
balance = new JLabel("New Balance " + Balance);
You set Balance to 0.00. With that being said, you will need to add:
balance.setText("New Balance " + Balance);
to give you the updated Balance.
I also noticed that the code you posted did not work if you left a text field blank. Look at the updated code below and try this.
public void actionPerformed(ActionEvent arg0) {
double strtblnc;
double dpst;
double wthdrw;
String sTxt = txt.getText();
String sTxt2 = txt2.getText();
String sTxt3 = txt3.getText();
if(sTxt.isEmpty())
sTxt = "0";
if(sTxt2.isEmpty())
sTxt2 = "0";
if(sTxt3.isEmpty())
sTxt3 = "0";
dpst = Double.parseDouble(sTxt2);//parses deposit;
strtblnc = Double.parseDouble(sTxt); //parses starting balance;
wthdrw = Double.parseDouble(sTxt3); //parses withdraw;
Balance = Balance + strtblnc + dpst - wthdrw;
balance.setText("New Balance " + Balance);
}

JAVA GUI won't calculate the price

I'm trying to make this application to calculate but it won't. Spend ages on it. I just want to calculate ones I press the button. I need it to display the correct price when clicking on the correct combo box. The prices have been set I think.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class retailsalescalcu extends JFrame {
//create the objects
JLabel department;
JLabel number;
JLabel name;
JLabel price;
JLabel discount;
JLabel sale;
JComboBox<String> dept;
JTextField itemNum;
JTextField itemName;
JTextField itemPrice;
JTextField itemDisc;
JTextField salePrice;
JButton calculate;
JButton clear;
public retailsalescalcu() {
//set object variables
super("Retail Sales Calculator"); //set window bar title
setSize(300, 300); //set window size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set window close
GridLayout grid = new GridLayout(7, 2);
setLayout(grid);
department = new JLabel("Department");
dept = new JComboBox<String>();
dept.addItem("Select");
dept.addItem("Men's Clothing");
dept.addItem("Women's Clothing");
dept.addItem("Shoes");
dept.addItem("Belts");
dept.addItem("Electronics");
dept.addItem("Hats");
//add ItemListener - JTextField & ComboBox
dept.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String)dept.getSelectedItem();
itemNum.setText(str);
} //end public void
}); //end item listener
number = new JLabel("Item Number");
itemNum = new JTextField(10);
name = new JLabel("Item Name");
itemName = new JTextField(10);
price = new JLabel("Original Price");
itemPrice = new JTextField(10);
discount = new JLabel("Discount");
itemDisc = new JTextField(10);
sale = new JLabel("Sale Price");
salePrice = new JTextField(10);
salePrice.setEditable(false);
calculate = new JButton("Calculate");
clear = new JButton("Clear");
//add objects to JFrame
add(department);
add(dept);
add(number);
add(itemNum);
add(name);
add(itemName);
add(price);
add(itemPrice);
add(discount);
add(itemDisc);
add(sale);
add(salePrice);
add(calculate);
add(clear);
//add event listener to calculate sale price
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent retail) {
String input1;
String input2;
double origPrice;
double percOff;
double clearance;
input1 = itemPrice.getText();
input2 = itemDisc.getText();
origPrice = Double.parseDouble(input1);
percOff = Double.parseDouble(input2)/100;
clearance = origPrice - (origPrice * percOff);
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
}
});
//add event listener to reset fields
clear.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent event) { //JButton event if clicked
dept.setSelectedIndex(0); //Combo Box will be empty and can be reset
itemNum.setText(null); //Item Number will be empty and can be reset
itemName.setText(null); //Item Name will be empty and can be reset
itemPrice.setText(null); //Item Price will be empty and can be reset
itemDisc.setText(null); //Item Discount will be empty and can be reset
salePrice.setText(null); //Item SalePrice will be empty and can be reset
}
});
setVisible(true);
} //end public retailsalescalcu
public static void main(String[] args) {
new retailsalescalcu();
} //end public static void
} //end public class retailsalescalcu
After debugging you code i found that you should remove/comment line #100 from your code
From
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
to
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
//salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
EDIT:
One problem is here:
//salePrice.setText(df.toString());
Comment that out and you will see your price after clicking Calculate. You are already setting salesPrice here:
salePrice.setText(df.format(clearance));
The toString() is not going to give you what you want.

Percents calculating part does not work in java

[Now working!] I have this code that should calculate percents (With some GUI). But the calculating part is not working... Maybe some of you know the answer? I think the problem is when I concert it from a string do a double. I'm from Sweden so I have a very crappy english. And all variable names were in swedish so I just translated them with googles translate.
package Java;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class java {
public static void main (String []args){
int frameSizeX = 500;
int frameSizeY = 135;
JPanel p = new JPanel();
p.setPreferredSize( new Dimension(frameSizeX,frameSizeY) );
JFrame f = new JFrame ("Percentage");
f.setSize(frameSizeX,frameSizeY);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.getContentPane().add(p);
JLabel cardiNum = new JLabel ("Cardinal number");
JTextField cardiNumField = new JTextField();
cardiNumField.setPreferredSize( new Dimension( 500, 24 ) );
final String talValue = (cardiNumField.getText());
JLabel perc = new JLabel("Percentage");
JTextField percField = new JTextField();
percField.setPreferredSize( new Dimension( 500, 24 ) );
final String proValue = (percField.getText());
double D = 0;
final JLabel answer = new JLabel("The answer is = " + D);
JButton butt = new JButton("Calculate");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double A = Double.parseDouble(talValue);
double B = Double.parseDouble(proValue);
double C = A/100;
double D = C*B;
answer.setText("The answer is" + D);
}
});
p.add(cardiNum, BorderLayout.AFTER_LINE_ENDS);
p.add(cardiNumField, BorderLayout.AFTER_LINE_ENDS);
p.add(perc, BorderLayout.AFTER_LINE_ENDS);
p.add(percField, BorderLayout.AFTER_LINE_ENDS);
p.add(butt);
p.add(answer);
f.pack();
f.setVisible(true);
}
}
You're getting the NullPointerException because you need to set those two strings only once the JButton has been clicked, inside the ActionListener.
Put these two lines:
final String talValue = (cardiNumField.getText());
final String proValue = (percField.getText());
inside the ActionListener for the JButton and make the cardiNumField and percField final and it should work. Alternatively, you can just remove those two variables and have:
double A = Double.parseDouble(cardiNumField.getText());
double B = Double.parseDouble(percField.getText());
As Martin Dinov mentions, the problem is that you were reading the contents of the text boxes before the user was able to write in them and click the button. That leads to a NumberFormatException, because you're trying to convert the empty String "" to a double. Therefore, you need to put that code inside the button click event handler. An extra change to fix this is that you need to make your text fields final. i.e.
final JTextField cardiNumField = new JTextField();
final JTextField percField = new JTextField();
That's because the button click handler is an anonymous inner class, so it can only read from final variables.
The following code fixes the problem I think you have been seeing.
public static void main(String[] args) {
int frameSizeX = 500;
int frameSizeY = 135;
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(frameSizeX, frameSizeY));
JFrame f = new JFrame("Percentage");
f.setSize(frameSizeX, frameSizeY);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.getContentPane().add(p);
JLabel cardiNum = new JLabel("Cardinal number");
final JTextField cardiNumField = new JTextField();
cardiNumField.setPreferredSize(new Dimension(500, 24));
JLabel perc = new JLabel("Percentage");
final JTextField percField = new JTextField();
percField.setPreferredSize(new Dimension(500, 24));
double D = 0;
final JLabel answer = new JLabel("The answer is = " + D);
JButton butt = new JButton("Calculate");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double cardinal = Double.parseDouble(cardiNumField.getText());
double percentage = Double.parseDouble(percField.getText());
double C = cardinal / 100;
double D = C * percentage;
answer.setText("The answer is " + D);
}
});
p.add(cardiNum, BorderLayout.AFTER_LINE_ENDS);
p.add(cardiNumField, BorderLayout.AFTER_LINE_ENDS);
p.add(perc, BorderLayout.AFTER_LINE_ENDS);
p.add(percField, BorderLayout.AFTER_LINE_ENDS);
p.add(butt);
p.add(answer);
f.pack();
f.setVisible(true);
}
Good luck with learning Java. You're obviously very new to it! :)

Using JTextField for user input

Thanks for your help guys...now the program works and runs like it should.. but I have 2 more question.
1.How can I get the output into a JTestField t4 or t5
2.How can I close the application using the JButton Buton3
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TriangleFarfan{
JFrame Triangle = new JFrame("Triangle Calculator");
JButton Button1 = new JButton ("Area");
JButton Button2 = new JButton("Perimeter");
JButton Button3 = new JButton("Close");
JTextField t1 = new JTextField(20);
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
JPanel j1 = new JPanel (new FlowLayout());
JLabel l1 = new JLabel("Enter side 1:");
JTextField t2 = new JTextField();
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
JPanel j2 = new JPanel (new FlowLayout());
JLabel l2 = new JLabel("Enter side 2:");
JTextField t3 = new JTextField();
String t3TextBox = t3.getText();
double side3 = Double.parseDouble(t3TextBox);
JPanel j3 = new JPanel (new FlowLayout());
JLabel l3 = new JLabel("Enter side 3:");
JTextField t4 = new JTextField();
JPanel j4 = new JPanel (new FlowLayout());
JLabel l4 = new JLabel("Area Result");
JTextField t5 = new JTextField(20);
JPanel j5 = new JPanel (new FlowLayout());
JLabel l5 = new JLabel("Perimeter Result");
public TriangleFarfan()
{
j1.add(l1);
j1.add(t1);
j2.add(l2);
j2.add(t2);
j3.add(l3);
j3.add(t3);
j4.add(l4);
j4.add(t4);
j5.add(l5);
j5.add(t5);
Triangle.add(j1);
Triangle.add(j2);
Triangle.add(j3);
Triangle.add(j4);
Triangle.add(j5);
Triangle.add(Button1);
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Triangle.add(Button2);
Button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Perimeter Button");
}
});
Triangle.add(Button3);
Button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Close Button");
}
});
Triangle.setLayout(new FlowLayout());
Triangle.setSize(450,400);
Triangle.setVisible(true);
Triangle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In addition to missing a main method, as Reimeus pointed out, your order of instructions is wrong. You are trying to read the user input before anything is even shown on the screen, and even before an object is created. For example, this line:
String t1TextBox = t1.getText();
tries to obtain a text from a TextBox that wasn't even added to a Panel that wasn't yet created.
To solve this, you need to rethink the logic of your program. Here are a few hints:
avoid assignments outside methods. Instead of writing
JFrame Triangle = new JFrame("Triangle Calculator");
declare the variable in the class body like this:
JFrame Triangle;
and assign it inside the constructor like this:
Triangle = new JFrame("Triangle Calculator");
Build the whole UI, then worry about listeners. This way you can be sure that you are not referencing an UI element that does not exist when getting the user input.
Get the user input inside the listeners, like this:
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// get the size of side1 from the textbox
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
// get the size of side2 from the textbox
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
// now we can calculate the area
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Add a main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TriangleFarfan();
}
});
}
The declaration
JTextField t1 = new JTextField(20);
doesn't set the value in the JTextField to 20. Instead it sets the number of columns for the JTextComponent but with an empty String. Therefore the line
double side1 = Double.parseDouble(t1TextBox);
will throw an NumberFormatException on startup.

Categories

Resources