[英]How to change JButton property?
I want to change button text when i click on it, but it does not appears on the GUI. 我想点击它时更改按钮文本,但它不会出现在GUI上。 In intellje IDE i can see it is changed but why does not appear in GUI?
在intellje IDE中,我可以看到它已被更改,但为什么没有出现在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);
}
}
});
than not possible without spliting code to to the two parts 不将代码拆分为两部分是不可能的
1) update JButton#setText
1)更新
JButton#setText
then 然后
2) executing rest of code 2)执行其余代码
javax.swing.Timer
javax.swing.Timer
进行delaing SwingWorker
SwingWorker
执行 Runnble#Thread
, Runnble#Thread
包装, 3) this code is executed on EDT, then all changes are done on EDT, end in same/one moment 3)此代码在EDT上执行,然后所有更改都在EDT上完成,以相同/一个时刻结束
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
: 在设置GUI以初始化按钮文本和
connState
时调用此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. 然后,您可以通过检查
connState
变量来connState
程序的当前状态,而不必在任何地方同步按钮字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.