Preferred way of getting the selected item of a JComboBox - java

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".

Related

can any one help me in this error in java?

i create hash table in java but there is aproblem in it when adding elements in it.
Hashtable <Integer,String> hashT=new Hashtable<Integer ,String >();
hashT.put<sum2 , g>;
the error in second line where define sum2 is variable contain integer value and g variable contain string value. i dont know where the problem in putting elements in hash table.i want to add the values of this variables in hash table each time as the values change.
To mutate an object, you have to call its properties. An object property is either a field or a method. In your case put is a method of the hashT object. A method call is done by writing the object name, then the dot operator, then the method name and finally the arguments surrounded by parenthesis:
objectName.methodName(argument1, argument2, ...);
The problem is here:
hashT.put<sum2 , g>;
put is a method and to call it you have to surround the arguments (sum2 and g) with parenthesis:
hashT.put(sum2, g);
You need to follow the comments and edit your title so its a meaningful title that will help other people understand what your question is about.
Also, when you get an error, copy the big red text that is displayed in the console (color depends on which editor you are using), also known as the error's "Stack Trace" and past it into your question somewhere. This will help us pinpoint what is going on, and the error title itself will likely give away to us exactly what's wrong.
However, without any context on what the error is and what is before or after those two lines of code it is difficult to determine if you have previously defined sum2 or g as a variable that stores values. I am going to assume you haven't assigned at least one of them, likely g as a variable.
For experimental purposes, try replacing those two lines of code with:
Hashtable <Integer,String> hashT=new Hashtable<Integer ,String >();
hashT.put<0 , "g">;
That is putting zero (0) as an explicit integer and g as an explicit string into the hashtable. If you need to put variables into there, then you need to define them before hand, like this:
int sum2 = 3 + 4;
String g = "Some String";
Hashtable <Integer,String> hashT=new Hashtable<Integer ,String >();
hashT.put<sum2 , g>;
Now the integer value 7 is stored as the hash and the string Some String as the mapped value.

How to compare 2 strings until a certain point each?

I need to compare 2 different strings with each other. I have String a and String b. String a holds a long string while String b tries to copy it via the users typing. String a is much larger than b. Is there a way to do this efficiently? So far the way i thought of it was for every button press it would run something along these lines of code.
splitTextA = fullTextA.substring(0, String b length );
if (splitText == String B)
change String change to a color green
else if false
change string change to a color red
A couple things, I dont know how to get the length of a string, i know how to split it though. and do you think this would work?
ps: sorry I dont know how to separate lines of code
this is not hw.. this is on my own Im just practicing.

JFrame Form add from JTextField to JList

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.

Choices for combobox in a repeat

I've got a view that contains documents with various questions I want answered about Purchase Orders.
Using a repeat, I list all the questions. There are a few different kinds of questions, so I only render the answer field that I need based on the FieldType column value. I want to pull the choices for a combobox from the DialogChoices field on the question document.
I'm currently getting the choices showing as plain text on the next line after the empty combobox instead of as the selectItems. Where is my code going wrong?
<xp:comboBox id="comboBox1">
<xp:this.rendered><![CDATA[#{javascript:rowData.getColumnValue("FieldType") == "Dialog Box"; }]]></xp:this.rendered>
<xp:selectItems>
<xp:this.value><![CDATA[#{javascript:var doc:NotesDocument = rowData.getDocument();
var choicesVector:java.util.Vector= doc.getItemValue("DialogChoices");
var choices = [];
// loop through the vector, doing push into the array
for (i=0; i<choicesVector.size(); i++) {
choices.push (choicesVector.elementAt(i))
};
return choices;}]]>
</xp:this.value>
</xp:selectItems>
</xp:comboBox>
Strange, but a test database with the code above does not seem to give me strange results. Maybe it is because the data is in fact not an Vector but just a string?
Here are some tips :
The first thing you could change in your code is the loop to get all the data out of your field. Since the value property of a combobox already expects an array or vector you can change the code to something like:
<xp:this.value><![CDATA[#{javascript:var doc:NotesDocument = rowData.getDocument();
return doc.getItemValue("DialogChoices");
}]]>
</xp:this.value>
But it would be even better to remove the getDocument call at all. If possible you can add a column to the view are you are using for the repeat's datasource. In this column you get the data from the field directory. This way you can use the viewentry's getColumnValue() which is a performance optimization. Something like:
<xp:selectItems>
<xp:this.value><![CDATA[#{try{
return rowData.getColumnValue("DialogChoices");
}catch(e){// do something }]]>
</xp:this.value>
</xp:selectItems>

Java - How to convert a Color.toString() into a Color?

In order to save Color attributes of a graphical object in my application, I saved the string representation of this Color in a data file.
For instance, for red I save: java.awt.Color[r=255,g=0,b=0].
How can I convert this string representation into a Color so that I can use it again after loading my data file ?
Thank you.
You may wish to use getRGB() instead of toString(). You can call
String colorS = Integer.toString(myColor.getRGB());
Then you can call
Color c = new Color(Integer.parseInt(colorS));
Using toString() "might vary between implementations." Instead save String.valueOf(color.getRGB()) for later reconstruction.
From the documentation of Color#toString
Returns a string representation of this Color. This method is intended to be used only for debugging purposes. The content and format of the returned string might vary between implementations. The returned string might be empty but cannot be null.
In other words, I wouldn't rely on being able to back-convert the string to the Color. If you insist on doing this, however, you can try to parse the numbers out of the string and hope that it will work with no guarantees.
Something like this seems to work for ME for NOW:
Scanner sc = new Scanner("java.awt.Color[r=1,g=2,b=3]");
sc.useDelimiter("\\D+");
Color color = new Color(sc.nextInt(), sc.nextInt(), sc.nextInt());
I don't recommend actually doing this, however.
I suggest you look into java's built-in serialisation technology instead. (I note that Color implements Serializable.)
Use the getRGB() method to get the int representation of the Color, then you save the int value and recreate the Color using that value. No parsing needed.
The easiest thing is to rethink the way you store the string representation. Get rid of all the labeling, and just store red as the string "0xFF0000". Then you can easily parse that string to get the single value for rgb, and send it to the Color constructor.
The alternative is to parse the more complicated string as you are now saving it "java.awt.Color[r=255,g=0,b=0]".
You can see the constructors for Color here:
http://java.sun.com/javase/6/docs/api/ (search "all classes" for Color).
Peter
Don't use the toString(). Use getRGB() / new Color(rgb) to save/restore the value of the color.
Stephan's answer helped me with this. However, I found that I needed to add a 'true' to the syntax in order to restore the color.
// convert to string
String colorS = Integer.toString(myColor.getRGB());
// restore colour from string
Color c = new Color(Integer.parseInt(colorS), true);

Categories

Resources