问题
I'm implementing a simple application in Java. I'm using the MVC module for the app. The problem is that when my Controller creates the objects of the View and the Model, when trying to use a simple get method I get the defaults values and not the new ones, that I inserted in the UI. Here is a code exmaple:
View:
public class Client extends JFrame {
private float ammount;
private JButton calculateButton;
...
public void startUI(ActionListener listener) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Client frame = new Client(listener);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
...
public Client(ActionListener listener) {
...
ammount = 10;
...
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(listener);
add(calculateButton);
...
public float getAmmount() {
return (float) this.ammount;
}
Controller:
public class Controller implements ActionListener {
private float result;
private Server server = new Server();
private Client client = new Client(this);
public Controller() {
server.rateParser();
client.startUI(this);
}
public void actionPerformed(ActionEvent e) {
result = client.getAmmount();
}
}
Main:
public class Program {
// Main function
public static void main(String[] args) {
Controller controller = new Controller();
}
}
So far so good, however, when I click the button and the action event triggers,
the getAmmount method returns -1, which is the default value. Same goes for all the getters in the Client class. Does any one knows why is this happening?
回答1:
You are initializing 2 clients.
First time is in the call inside main
Controller controller = new Controller();
When you initialize a class, all its members are initialized too. Since Client is a member of Controller:
public class Controller implements ActionListener {
private Client client = new Client(this); // 1st initialization
}
it is initialized with a new Controller() call.
Second time is the call in the constructor
public Controller() {
server.rateParser();
client.startUI(this); // <---- here
}
Leaving the fuzz out of startUI, it is:
public void startUI(ActionListener listener) {
Client frame = new Client(listener); // 2nd initialization
frame.setVisible(true);
}
Since actionPerformed is inside Controller, it is its field client that is called in result = client.getAmmount();. That one is remained untouched throughout the program's lifetime and thus returns the defaults (which were created in its initialization). However, the client you display is the second one, frame, for which you call frame.setVisible(true);. That one is modified, but its values are never read.
来源:https://stackoverflow.com/questions/30295418/actionlistener-gets-default-values