I have two classes, Window and Register, I catch a String in Window then i need to use in Register. Here is a piece of my code:
public class Window extends JFrame{
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Window() {
Interface();
}
public void Interface(){
botonContinuar = new JButton("Next");
botonContinuar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//This get the value from my list...
setCity((String) listaCity.getSelectedValue());
Register open=new Register();
}
});
botonContinuar.setBounds(164, 203, 89, 42);
panel.add(botonContinuar);
}
public class Register extends Window{
public Register() {
Window window=new Window();
System.out.println(window.getCity());
}
Output is :null:, when i was expecting the city catched from the list in Window. I'm new with Java, but I suppose the problem is that im creating a new Window objetc then all my atributes got initialized, but I cant figure out how to avoid this.
Thanks in advance
When you will use this constructor, the city property will be initialized and you will see your output. Witoout it, the city remains null
.
Window window=new Window("New York");
System.out.println(window.getCity());
Another option is to use public void setCity(String city)
method, like:
Window window=new Window();
window.setCity("New York");
System.out.println(window.getCity());
Couple of things:
If you need default value, i would suggest you initialize it like:
private String city = "defaultValue"; //or modify constructor to pass city value when object initializes.
I see two problems
actionPerformed
action for the city to be set. Here are some suggestions:
new Window()
, or Window calls new Register()
but not both.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.