I'm looking at this thread, and while I can run it normally by copying the code, I don't understand the syntax and logic of the following line. I have searched for answers but I only find how to write code and not the explanation of it. I copy code from the constructor to not make it so long.
public Formulario() {
setLayout(null);
combo1=new JComboBox();
combo1.setBounds(10,10,80,20);
add(combo1);
combo1.addItem("rojo");
combo1.addItem("vede");
combo1.addItem("azul");
combo1.addItem("amarillo");
combo1.addItem("negro");
combo1.addItemListener(this);
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource()==combo1) {
String seleccionado=(String)combo1.getSelectedItem(); //ESTA LINEA NO ENTIENDO
setTitle(seleccionado);
}
}
What I don't understand is what does that parenthesis do (String)
in front of the object combo1
. The tutorial I'm looking at doesn't explain it and I've never seen such a syntax before. What does it mean and what is it for?
Sorry if the question is strange, but from the logical point of view, it seems redundant to me (since I understand that it cannot be loaded int
in the JComboBox
) and from the syntactic point of view it is the first time that I see that a parenthesis is put in front of it. Since I doubt that it is a whim, I suppose there is an explanation.
The method
getSelectedItem()
returns a data of typeObject
, therefore the variableseleccionado
that is of typeString
, could not take this data, for this a recasting or (as it is mostly known) casting must be done , which basically consists of converting an object type in other.Could also be used:
There are two types of casts:
Implicit:
(<Tipo de dato>) <valor>
explicit:
(<Tipo de dato>) <valor>
To find out which one to use:
either
Source: What is Casting and what is it for?
First, I'd like to put you in context: if you look at the documentation for the JComboBox control ( https://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html ), you'll see that the method
getSelectedItem()
returns a value of type Object . With this in mind, you cannot access what an Object type is representing since it is too generic , so a String is cast using the () operator before a statement, i.e., the Object and accesses with the structure of a String object . This is done because each element that has been added to the JComboBox is a String (you can see it on each linecombo1.addItem()
) , so the type of the elements of the JComboBox is known in advance . I hope I have explained myself.All the best.