on button click update jttextfield and calculate with newly entered value? - java

In my Java GUI there are 4 JTextFields. The goal is to enter default values for 3 textfields (example .8 in code below) and calculate the value and display the calculation into the 4th textfield. The user should then be able to change the values of the numbers within the JTextField and then press the calculate button again to get the new values to recalculate and display them.
Problem: when the JTextfields are edited and the calculate button is pressed it does not calculate with the new numbers but instead with the old initial values.
JTextField S = new JTextField();
S.setText(".8");
String Stext = S.getText();
final double Snumber = Double.parseDouble(Stext);
.... *same setup for Rnumber*
.... *same setup for Anumber*
....
JButton btnCalculate_1 = new JButton("Calculate");
btnCalculate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int valuec = (int) Math.ceil(((Snumber*Rnumber)/Anumber)/8);
String stringValuec = String.valueOf(valuec);
NewTextField.setText(stringCalc);
}
I have checked several posts and tried:
How Do I Get User Input from a TextField and Convert it to a Double?
Using JTextField for user input
for the basics. However whenever trying to adapt it to my code eclipse returns various errors.

use S.getText() inside the actionPerformed() method.
The code inside actionperformed block is invoked on the button press and the code outside it remains unaffected.
So once you run your code and insert values to text fields, it assigns the a value but it does not change the same when you change the value and press calculate button

try using This code.
class a extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
a()
{
setLayout(null);
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
JButton B1 = new JButton("Calculate");
t3.setEditable(false);
t1.setBounds(10,10,100,30);
t2.setBounds(10,40,100,30);
t3.setBounds(10,70,100,30);
B1.setBounds(50, 110, 80, 50);
add(t1);
add(t2);
add(t3);
add(B1);
B1.addActionListener(this);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new a();
}
#Override
public void actionPerformed(ActionEvent e)
{
double Snumber = Double.parseDouble(t1.getText());
double Rnumber = Double.parseDouble(t2.getText());
double Anumber = Snumber+Rnumber;
t3.setText(String.valueOf(Anumber));
}
}

Related

java Fahrenheit to celsius and vice versa converter in jframe

I have an assignment where I have to create a Fahrenheit to Celsius (F2C) converter and vice versa. It is in a jframe where there are 3 buttons and 2 text fields.
The first text field will be the input temperature. The second text field will have the converted temperature.
The first button called F2C will convert the number entered from the first text field to Celsius and place it in the second text field.
The second button called C2F will also take the number entered from the first text field and convert it into Fahrenheit and place it in the second text field.
the third button will exit the jframe.
I have most of the code for the layout of the buttons and text field working. The exit button is also working.
My problem is getting the data from the first text field, pressing the F2C button to convert to Celsius, then placing the converted number back into the second text field. Same thing when pressing the C2F button to convert to Fahrenheit.
here's my code so far:
import javax.swing.*; // for GUI
import java.awt.*; // for GUI
import java.awt.color.*; // for Color
import java.awt.event.*; // for events
public class JButtonDemo extends JFrame implements ActionListener
{
JButton jbC2F;
JButton jbF2C;
JButton jbExit;
TextField tfInput;
TextField tfOutput;
public JButtonDemo()
{
int width = 267;
int height = 400;
setTitle("First Frame"); // set title of JFrame
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width - width)/2, (d.height - height)/2);
/** ***********************************************
*
* create buttons
* register buttons
*************************************************/
// make jbExample and jbExit
jbC2F = new JButton("C2F");
jbF2C = new JButton("F2C");
jbExit = new JButton("exit");
tfInput = new TextField(" ");
tfOutput = new TextField(" ");
// register buttons
jbExit.addActionListener(this);
jbC2F.addActionListener(this);
jbF2C.addActionListener(this);
// create Panel Buttons default to Flow
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
buttons.setBackground(Color.BLUE);
// add buttons to panel
buttons.add(jbC2F);
buttons.add(jbF2C);
buttons.add(jbExit);
/** **************************************************
*
* create content Container
***************************************************/
// create container
Container content = getContentPane();
content.setBackground(Color.BLUE);
content.setLayout(new FlowLayout());
content.add(tfInput);
content.add(tfOutput);
// add panels
content.add(buttons, BorderLayout.NORTH);
} // end constructor
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
//test for exit button
if(source == jbExit)
{
System.exit(0);
}
}
public static void main(String args[])
{
JButtonDemo fl = new JButtonDemo();
fl.setVisible(true);
}
}
Do it as follows:
public void actionPerformed(ActionEvent ae) {
double t = Double.parseDouble(tfInput.getText().trim());
Object source = ae.getSource();
// test for exit button
if (source == jbExit) {
System.exit(0);
} else if (source == jbC2F) {
tfOutput.setText(String.valueOf(t * 9.0 / 5.0 + 32.0));
} else if (source == jbF2C) {
tfOutput.setText(String.valueOf((t - 32.0) * 5.0 / 9.0));
}
}
For your answer
You can add an ActionListener to your buttons and remove the implementation of the ActionListener in your class.
For example:
jbC2F.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Parse tfInput.getText() to integer
...
//Set tfOutput to the result with tfOutpput.setText(String str)
...
}
});
And then you parse your text to an integer using Integer.parse(String str) which should be the content of the corresponding text field. You might want to add a try - catch block to catch exceptions thrown by the parse method when the string could not be parsed to a valid integer.
Side note
You can replace
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width - width)/2, (d.height - height)/2);
By
setLocationRelativeTo(null)
This will also center your application to the middle of the screen
Here's an example. You will need to check for exceptions in case of non-numeric input. JFormattatedTextField's could help with that. You will also need to determine which button is pressed so you can do the proper conversion.
public void actionPerformed(ActionEvent ae)
{
String temp = tfInput.getText();
if (!temp.isBlank()) {
double v = Double.valueOf(temp);
double celcius = (v-32)*5/9.;
temp = String.format("%4.2f", celcius);
tfOutput.setText(temp);
}
Object source = ae.getSource();
//test for exit button
if(source == jbExit)
{
System.exit(0);
}
}

Having trouble giving my JPanel functionality

*This is my first time using GUI, I seem to miss something my eye can't catch. The code looks fine to me however when i submit it to autoLab I get this error, which I cannot figure out where I went wrong.
{"correct":false,"feedback":"(class java.lang.NumberFormatException)
Error while attempting to call static method q2() on input [1]}
The problem question is q5:
Write a public static method named q5 that takes no parameters and returns a JPanel.
The panel will contain 1 JTextField with any number of columns, 1 JButton with any label,
and 1 JLabel. The panel will have functionality such that when a user enters a number into
the text field (we'll call this value x) and presses the button the label will display the
y-value of a parabola in standard form (https://www.desmos.com/calculator/zukjgk9iry)
where a=5.37, b=-6.07, and c=2.0 at the x-value from the text field
Hint: If you store y in the wrapper class Double instead of the primitive double you can
call toString on it to convert it to a string that can be used as the text for the label
Tip: After clicking the button you may have to resize your window to see the result since
the frame will not automatically resize to fit the new text
Do not create any JFrames in your problem set questions. Doing so will crash the
auto-grader since the grading server does not have a screen to display the JFrame.
Instead, only return the required JPanel in the problem set methods and test with a JFrame
in your main method, or other helper methods that are not graded
This is the code I wrote
public static JPanel q5() {
JPanel panel = new JPanel();
JTextField textField = new JTextField(5);
panel.add(textField);
JLabel label = new JLabel("hello!");
panel.add(label);
JButton button = new JButton("Click Me!");
panel.add(button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int x = Integer.parseInt(textField.getText());
double a=5.37*Math.pow(x, 2);
double b=-6.07*x;
double c=2.0;
String answer= ("y = " + a+ b +c);
label.setText(answer);
}
});
return panel;
}
can you explain where I went wrong , thank you.
So, a NumberFormatException can occur when trying to parse a String, when the String does not contain a number. You did not give enough information to be sure, but I am going to presume that it is this line that causes the problem:
int x = Integer.parseInt(textField.getText());
One thing that strikes me as odd, is that you initialize the JTextField with 5 columns:
JTextField textField = new JTextField(5);
Is that what you want? If you wanted to pre-initialize the text field with a value of 5, you would have to do it like this:
JTextField textField = new JTextField("5");

Value from JSpinner not appearing when called (SWING)

i have a question regarding my jspinner, i figured out how to get the value by using the jspinner.getvalue(); method. but what i need to accomplish is the value from the spinner to be printed onto a panel that at the time is hidden, (it will be visible once the user presses on the "order" section of my program) here is the components of my code regarding my spinner, the button "add to order" which is supposed to add the variable from the jspinner to the textbox in the panel. then i will also show the code for my panel
spinner
int min = 0;
int max = 9;
int step = 1;
int initValue = 0;
SpinnerModel model = new SpinnerNumberModel(initValue, min, max, step);
JSpinner a1 = new JSpinner(model);
a1.setBounds(6, 200, 33, 26);
contentPane.add(a1);
JFormattedTextField tf = ((JSpinner.DefaultEditor) a1.getEditor()).getTextField();
tf.setEditable(false);
tf.setBackground(Color.white);
the add to order button which is supposed to print the variable from the spinner to the panel
JButton btnAddToOrder = new JButton("Add To Order");
btnAddToOrder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
and finally my panel
orderDeet = new JTextField((Integer) a1.getValue());
orderDeet.setEditable(true);
orderDeet.setBounds(20, 33, 296, 235);
panel.add(orderDeet);
orderDeet.setColumns(10);
i can also show the code for the button to make the panel visible if needed but i dont want to make the question too complicated.

Adding 2 Integers using AWT

I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)
You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});
Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.
Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered

Attempting to change JTextFields Using Buttons

I am attempting to get the next set of values to display in the JTextFields after hitting the next button. I am new to programming so I am not really sure what I am missing. What I want to occur is when I hit the next button when the window displays the next set of values will now display in the appropriate JTextFields unfortunately what ends up happening is nothing. I have tried several different ways of getting this to work and so far nothing. I know it is not the button its self because if I change the actionPerformed next to say setTitle(“5000”) it will change the title within the window. Any help is appreciated.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame implements ActionListener {
JButton next;
JButton previous;
JButton first;
JButton last;
private JLabel itmNum = new JLabel("Item Number: ", SwingConstants.RIGHT);
private JTextField itemNumber;
private JLabel proNm = new JLabel ("Product Name: ", SwingConstants.RIGHT);
private JTextField prodName;
private JLabel yr = new JLabel("Year Made: ", SwingConstants.RIGHT);
private JTextField year;
private JLabel unNum = new JLabel("Unit Number: ", SwingConstants.RIGHT);
private JTextField unitNumber;
private JLabel prodPrice = new JLabel("Product Price: ", SwingConstants.RIGHT);
private JTextField price;
private JLabel restkFee = new JLabel("Restocking Fee", SwingConstants.RIGHT);
private JTextField rsFee;
private JLabel prodInValue = new JLabel("Product Inventory Value", SwingConstants.RIGHT);
private JTextField prodValue;
private JLabel totalValue = new JLabel("Total Value of All Products", SwingConstants.RIGHT);
private JTextField tValue;
private double toValue;
int nb = 0;
char x = 'y';
public GUI()
{
super ("Inventory Program Part 5");
setSize(800,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
first = new JButton("First");
previous = new JButton("Previous");
next = new JButton("Next");
last = new JButton("Last");
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
Movies[] titles = new Movies[9];
titles [0] = new Movies(10001, "King Arthur", 25 , 9.99, 2004, .05);
titles [1] = new Movies(10002,"Tron", 25, 7.99, 1982, .05);
titles [2] = new Movies(10003, "Tron: Legacy",25,24.99,2010,.05);
titles [3] = new Movies(10004,"Braveheart", 25,2.50,1995,.05);
titles [4] = new Movies(10005,"Gladiator",25,2.50,2000,.05);
titles [5] = new Movies(10006,"CaddyShack SE",25,19.99,1980,.05);
titles [6] = new Movies (10007,"Hackers",25,12.50,1995,.05);
titles [7] = new Movies (10008,"Die Hard Trilogy",25,19.99,1988,.05);
titles [8] = new Movies (10009,"Terminator",25,4.99,1984,.05);
Arrays.sort (titles, DVD.prodNameComparator);
itemNumber.setText(Double.toString(titles[nb].getitemNum()));
prodName.setText(titles[nb].getprodName());
year.setText(Integer.toString(titles[nb].getYear()));
unitNumber.setText(Integer.toString(titles[nb].getunitNum()));
price.setText(Float.toString(titles[nb].getprice()));
rsFee.setText(Double.toString(titles[nb].getRestkFee()));
prodValue.setText(Double.toString(titles[nb].getprodValue()));
tValue.setText("2636");
setLayout(new GridLayout(8,4));
add(itmNum);
add(itemNumber);
add(proNm);
add(prodName);
add(yr);
add(year);
add(unNum);
add(unitNumber);
add(prodPrice);
add(price);
add(restkFee);
add(rsFee);
add(prodInValue);
add(prodValue);
add(totalValue);
add(tValue);
add(first);
add(previous);
add(next);
add(last);
setLookAndFeel();
setVisible(true);
}
public void updateFields()
{
itemNumber.getText();
prodName.getText();
year.getText();
unitNumber.getText();
price.getText();
rsFee.getText();
prodValue.getText();
tValue.getText();
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == next)
{
nb++;
}
}
private void setLookAndFeel()
{
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println("couln't use the system"+ "look and feel: " + e);
}
}
}
Your ActionListener only has one assignment
nb = 1;
and a repaint. This does not update the JTextFields with the values from your Movies array titles. You need to do this explicitly.
itemNumber.setText(Double.toString(titles[nb].getItemNum()));
...
To make this possible, you will need to make your Movies titles array a class member variable so that it can be accessed from your ActionListener.
Also you never actually change the value of nb in your ActionListener. As it's a "next" button, you will probably want to increment it:
nb++;
Side Notes:
Java uses camelcase which would make the method getitemNum getItemNum.
An ArrayList would give you more flexibility for adding Movie titles over an array which is fixed in size.
I think the logic of chaning JTextFields is inside the constructor of GUI class. So unless you are creating another object of GUI class, which I can see it is not being created. Your JTextFields will not be updated.
So basically to solve this problem you will have to move your logic of changing JTextFields inside another method like for example
public void updateFields(){
//place your logic code here
}
and then from actionPerformed method call this updateFields() method
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == next)
{
nb =1;
}
updateFields();
///repaint(); /// you don't need the repaint method
}
As per your question in the comments and as far as my understanding is concerned place your titles array outside the constructor, and do the following changes so it will look something like this:
private JTextField tValue;
private double toValue;
int nb = 0; //note initialize this to 0
Movies[] titles = new Movies[9];//this is the line that comes out of the Constructor
public GUI()
{
///inside the constructor do the following changes
for (int i = 0; i < titles.length; i ++)
{
toValue += (titles[i].gettotalVal());
}
//note I will be accessing the 0th position of the array assuming you need the contents of the first objects to be displayed
itemNumber = new JTextField(Double.toString(titles[0].getitemNum()));
prodName = new JTextField(titles[0].getprodName());
year = new JTextField(Integer.toString(titles[0].getYear()));
unitNumber = new JTextField (Integer.toString(titles[0].getunitNum()));
price = new JTextField (Float.toString(titles[0].getprice()));
rsFee = new JTextField (Double.toString(titles[0].getRestkFee()));
prodValue = new JTextField(Double.toString(titles[0].getprodValue()));
tValue = new JTextField ("2636");
nb = 0;
//if (nb == 0) you don't need a if statement
//{
next.addActionListener(this);
//}
///Now for the updateFields() method
public updateFields(){
nb++;
itemNumber.setText(Double.toString(titles[nb].getitemNum());
prodName.setText(titles[nb].getprodName());
year.setText(Integer.toString(titles[nb].getYear()));
unitNumber.setText(Integer.toString(titles[nb].getunitNum()));
price.setText(titles[nb].getprice()));
rsFee.setText(Double.toString(titles[nb].getRestkFee()));
prodValue.setText(Double.toString(titles[nb].getprodValue()));
}

Categories

Resources