Reputation: 197
I want to change button text when i click on it, but it does not appears on the GUI. In intellje IDE i can see it is changed but why does not appear in GUI? This is code snip:
final WebLabel loading = new WebLabel("Disconnected...", IconLib.ICON_19X17_THICK_ARROW_RIGHT_LIGHTBLUE.getIcon(), SwingConstants.CENTER);
final WebLabel ipLabel = new WebLabel(host);
final JPanel horizontalMiddlePanel = new JPanel();
final WebButton disconnect = new WebButton("Connect", IconLib.ICON_16X16_QUESTIONMARK_ON_BLUE_CIRCLE.getIcon());
disconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (loading.getText().equals("Connected...")) {
loading.setText("Disconnected...");
loading.setIcon(IconLib.ICON_19X17_THICK_ARROW_RIGHT_LIGHTBLUE.getIcon());
disconnect.setText("Connect");
} else {
loading.setText("test");
loading.setIcon(IconLib.ICON_19X17_THICK_ARROW_RIGHT.getIcon());
ipLabel.setText(ipLabel.getText().replace(" Unreachable try again",""));
ipLabel.setForeground(Color.green);
disconnect.setText("Connecting");
callflexConnection(ipLabel, 3001, loading, disconnect);
}
}
});
Upvotes: 0
Views: 366
Reputation: 109813
than not possible without spliting code to to the two parts
1) update JButton#setText
then
2) executing rest of code
javax.swing.Timer
SwingWorker
Runnble#Thread
, 3) this code is executed on EDT, then all changes are done on EDT, end in same/one moment
Upvotes: 2
Reputation: 50041
It's hard to tell if it's the source of your current problem or not, but performing logic in code based on the current text on a button is a flimsy way to do things. You should maintain that connection state in a dedicated variable. Something like this:
private enum ConnState {
CONN_DISCONNECTED,
CONN_CONNECTING,
CONN_CONNECTED,
};
private ConnState connState;
private void setConnState(ConnState connState) {
this.connState = connState;
switch (connState) {
case CONN_DISCONNECTED:
loading.setText("Disconnected");
disconnect.setText("Connect");
break;
case CONN_CONNECTING:
loading.setText(...etc...);
disconnect.setText(...);
break;
case CONN_CONNECTED:
loading.setText(...);
disconnect.setText(...);
break;
}
}
And call this when setting up the GUI to initialize the button text and connState
:
setConnState(CONN_DISCONNECTED);
Then you can reason robustly about the current state of the program by checking the connState
variable instead of having to synchronize button strings everywhere.
Upvotes: 0