JFrame Form add from JTextField to JList - java

I'm trying to make a contact field where you can type in a first name and a last name in two separate text fields and click the "Add" button I created to send it to the list, but I'm unsure of how to do this exactly, being new to jFrame. I was using something in a tutorial that was similar to this using floats (which is shown below), only because I wasn't sure how to use the "String" variation, however this only seems to work when the "setText" command is set on another text field and won't work on a jList.
float num1, num2, result;
num1 = Float.parseFloat(textFieldFirstName.getText());
num2 = Float.parseFloat(textFieldLastName.getText());
result = num1+num2;
listFieldContact.setText(String.valueOf(result));
Are there any ideas or even good resources out there for jFrame? I've looked in a lot of places but they never quite seem to have exactly the information I need.

this only seems to work when the "setText" command is set on another text field and won't work on a jList.
A JList doesn't have a setText(...) method. You need to update the ListModel.
Read the section from the Swing tutorial on How to Use Lists for a working example that does almost exactly what you want.
The example uses a single text field by you should easily be able to get it to work with two text fields.

Try:
String fname = textFieldFirstName.getText();
String lname = textFieldLastName.getText();
listFieldContact = fname + " " + lname;
You don't need float conversion, as MadProgrammer pointed out. You do need a space between first and last name. Maybe you want lname + ", " + fname in other circumstances.

I think to make the values available in the JList it is not necessary to use Float for string operation. We can do it like this :
Vector<String> nameVector = new Vector<>();
JList<String> nameList = new JList<>();
public void addText() {
nameVector.add(firstNameTF.getText()+lastNameTF.getText());
nameList.setListData(nameVector);
}
I think this piece of code will help you to solve your query.

Related

Multiplication Field in Java / SceneBuilder

I'm a java Beginner and I've created a program where you can type in some food in a TableView and the details of the respective food you can type in a GripPane. One of the Details you have to type in is the quantity of the food, and another is the Calories per piece. Now I would like to create a button and a field. Or Maybe just a field that shows all calories of the food in the Table view. So it should multiplicate the quantity with the calories, for every food and add them all together. For a Total of Calories. Now I have no idea how to do that. Could somebody help me with step-by-step instructions? Not sure if it makes sense to add some code to the program. By the way, I use Eclipse on Windows and SceneBuilder. Thanks for every help.
Cheers Blarg
The first piece of advice from my side would be to try writing some code on your own! That way you learn and you wouldn't need to copy and paste somebody else's code.
And secondly, this is how I would approach it:
Create the fields as you described below in the Scene Builder and give them all id (names) so that we can access them in our controller (I am supposing you know how that works).
Add a button so that the user can click to perform the calculation
When the button is clicked, you can get all the information from each TextBox and create a Food Object with all the information. Performing the calculation is a rather simple task that can be done by converting the data received from the TextBoxes into numbers and multiplying
public void addFoodItemIntoTable()
{
...
String quantityOfFoodStr = quantityTextBox.getText();
int quantityOfFood = Integer.parseInt(quantityOfFoodStr);
String caloriesOfFoodStr = caloriesTextBox.getText();
double caloriesOfFood = Double.parseDouble(caloriesOfFoodStr);
double total = quantityOfFood * caloriesOfFood;
...
}
After adding all the elements in your TableView (Check this). You can easily get the total of the field by iterating all the elements of your table and adding them into a variable.
Example:
double total = 0;
for(Food currentFood : foodTable.getItems())
{
total = total + currentFood.getTotalCalculation(); // The naming should not be correct... Change it to whatever you find suitable
}
Good luck!

JAVA How to align text in JTextArea regardless of length of characters

Here is a picture of my JTextArea:
Here is my code:
String display = "";
display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);
What should I do so that the texts are aligned properly regardless of the length of characters of the words?
As much as possible I want to use JTextArea not JTable (since I'm not familiar with it yet)
Thank you in advanced!
Use a JTextPane instead of JTextArea, as that can do HTML. Then add an HTML <table>. Probably with some styles.
StringBuilder display = new StringBuilder("<html><table>");
display.append("<tr><td align='right'>").append(num)
.append("</td><td>").append(name)
.append("</td><td align='right'>").append(stocks)
.append("</td><td>").append(req)
.append("</td></tr>");
display.append("</table>");
txtPane.setText(display.toString());
This allows proportional fonts and styled text like bold, red, background colors.
As mentioned by #AndyTurner above your best approach is to rely on the String formatter to set the character width of each variable to print with also the ability to right or left justified. So in your case, as you left justified everything it could be something like that:
txtArea.setText(String.format("%-3s%-20s%-5s%-5s%n", num, name, stocks, req));
In this example I allocated 3 characters for num, 20 for name and 5 for stocks and req.
More details here
I want to use JTextArea not JTable (since I'm not familiar with it yet)
Well, now is the time to become familiar with a JTable. Use the proper component for the job, that is why multiple components exist. Don't try to fit a square peg in a round hole.
A JTextArea is not the appropriate component for that kind of formatting.
Instead you should be using a JTable. A JTable is designed to display data in a row/column format. Check out the section from the Swing tutorial on How to Use Tables for more information and working examples.
If you must use a text component then use a JTextPane. You can manually set the value of a tab so all the text is aligned. The problem with this approach is again you need to determine what the size of each tab should be. So this means either you make a random guess at the size of each column or you iterate through all the data to determine the size. Of course this complicates the code. See: Java Setting Indent Size on JTextPane for an example.
Again, the better solution is to learn to use Swing how it was designed to be used.
String display = "";
// just add values accordingly the best way to get the result you
// want is to mess around with formatting until you have the values
// where you want them in the textfield.
display = String.format("%20s %10s%n", value1, value2);
//display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
// stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);

use setText() on multiple labels using for loop in Java (Netbeans)

I have created multiple labels in design mode and named them as lab_1, lab_2, lab_3 and so on.
Now I want to use setText() on them using a for loop.
for(int i=0; i<16; i++){
String var= "lab_"+i;
var.setText(i);
}
This obviously didn't work. But I'm unable to think of something else.
Is it possible to change the labels into an array of labels now(I haven't created them dynamically instead I created them from the design window.)
Any help?
You want something like this??.
String EMPTY_SPACE="";
JLabel [] jLabels ={lab_1, lab_2, lab_3};
for (int i = 0; i < jLabels.length; i++) {
jLabels[i].setText(i+EMPTY_SPACE);
}
Ignore the loop and focus on these two lines
String var= "lab_"+i;
var.setText(i);
you are trying to call setText on var which is a string. Since your title talk about label and your example about setText, I believe you want to set the text of JLabel using it setText method.
To solve your issue, simply change your variable names.
Note that even if it will probably solve the compiler error (that you did not tell us you had) that you had, your program will probably not work as expected.
If you expect a concatenation of each string in your label, then at each setText call you must retrieve the actual text and concatenate.

JFormattedTextField and PropertyChangeListener event.getOldValue() and event.getNewValue() returning null

As the title suggests, I have the following listener on a JFormattedTextField:
myFormattedTextField.addPropertyChangeListener("value", new PropertyChangeListener()
{
#Override
public void propertyChange(PropertyChangeEvent evt)
{
System.out.println("Old value: " + evt.getOldValue());
System.out.println("New value: " + evt.getNewValue());
}
});
This always prints out null for both getOldValue() and getNewValue().
If I remove "value" string as a parameter, I get even weirder results, like the JPanel the textField is residing in or true/false values.
What exactly am I missing here?
What exactly am I missing here?
It's hard to tell exactly what is the problem based on your snippet. However be aware that JFormattedTextField component works along with both an AbstractFormatterFactory and an AbstractFormatter to be able to convert from a String representation to an Object value and the other way around.
If you initialize the formatted text field as follows, then both formatter and formatter factory will be null and no value could be ever converted: thus it will always be null:
JFormattedTextField textField = new JFormattedTextField(); // default empty constructor
If this is the case then you have an explanation about what is happening. If you take a look JFormattedTextfield class' constructors all of them take parameters that will help the component to initialize both formatter and formatter factory, except for empty constructor.
For a better understanding please have a look to How to Use Formatted Text Fields tutorial.
Side note
You say in a comment:
I am not using a NumberFormatter. Since the text fields can be blank to start with.
It's irrelevant if you want the text field be blank at the start: just don't set any value to the text field and leave the user change it (of course initial value will be null). But you definitely need to set a formatter.
if you are using NumberFormatter this may solve your problem:
numberFormatter.setCommitsOnValidEdit(true);

Preferred way of getting the selected item of a JComboBox

HI,
Which is the correct way to get the value from a JComboBox as a String and why is it the correct way. Thanks.
String x = JComboBox.getSelectedItem().toString();
or
String x = (String)JComboBox.getSelectedItem();
If you have only put (non-null) String references in the JComboBox, then either way is fine.
However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.
To be robust against null values (still without casting) you may consider a third option:
String x = String.valueOf(JComboBox.getSelectedItem());
The first method is right.
The second method kills kittens if you attempt to do anything with x after the fact other than Object methods.
String x = JComboBox.getSelectedItem().toString();
will convert any value weather it is Integer, Double, Long, Short into text
on the other hand,
String x = String.valueOf(JComboBox.getSelectedItem());
will avoid null values, and convert the selected item from object to string
Don't cast unless you must. There's nothign wrong with calling toString().
Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String out of an Object[]?"
JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.
mycombo.addItem("Hello Nepal"); //Adds data to the JComboBox.
String s=String.valueOf(mycombo.getSelectedItem()); //Assigns "Hello Nepal" to s.
System.out.println(s); //Prints "Hello Nepal".

Categories

Resources