我目前正在开发一个交互式用户界面,可以显示您是否打开了温室系统的水或照明组件。
当从另一个将标志值传递给线程类的窗口单击按钮时,使标签图标发生变化时,我遇到了相当大的挑战,这反过来会使图标发生变化
控制器 - > ThreadLogic - > NewSim
这是我在UI窗口中使用的一些示例测试代码 我还是初学者,所以我使用的是eclipse中自动生成的代码
粘贴代码似乎有些问题
这是我用来修改标志值的测试代码段
ThreadLogic
while(!t.interrupted()){
sim = new NewSim();
try {
sim.setLightStatus(1);
System.out.println("flag is 1");
t.sleep(5000);
sim.setLightStatus(0);
System.out.println("flag is 0");
t.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
//VS4E -- DO NOT REMOVE THIS LINE!
public class NewSim extends JFrame {
private static final long serialVersionUID = 1L;
protected JLabel water;
protected JLabel light;
Icon waterIcon = null;
Icon lightIcon = null;
private int lightFlag = 0;
private JPanel iconPane;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public NewSim() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getIconPane(), new Constraints(new Leading(4, 313, 10, 10), new Leading(4, 232, 10, 10)));
setSize(320, 240);
}
private JPanel getIconPane() {
if (iconPane == null) {
iconPane = new JPanel();
iconPane.setLayout(new GroupLayout());
iconPane.add(getWaterLabel(), new Constraints(new Leading(163, 10, 10), new Leading(79, 12, 12)));
iconPane.add(getLightLabel(), new Constraints(new Leading(115, 12, 12), new Leading(79, 12, 12)));
}
return iconPane;
}
private JLabel getLightLabel() {
if (light == null) {
light = new JLabel();
System.out.println(this.lightFlag);
setLightStatus(0);
}
return light;
}
private JLabel getWaterLabel() {
if (water == null) {
water = new JLabel();
water.setIcon(new ImageIcon(getClass().getResource("/images/wateroff.png")));
}
return water;
}
public void setLightStatus(int lightFlag2) {
// TODO Auto-generated method stub
this.lightFlag = lightFlag2;
switch(this.lightFlag){
case 0: System.out.println("case 0");
light.setIcon(new ImageIcon(getClass().getResource("/images/lightoff.png")));
light.revalidate();
break;
case 1: System.out.println("case 0");
light.setIcon(new ImageIcon(getClass().getResource("/images/lighton.png")));
light.revalidate();
break;
}
}
}
答案 0 :(得分:0)
在Swing中,除了Event Dispatch Thread(EDT)之外,你不能在任何其他线程中创建或修改swing组件。
因此,应在EDT中执行以下行:
sim = new NewSim();
sim.setLightStatus(1);
sim.setLightStatus(0);
使用SwingUtilities.invokeLater()在EDT中执行某些代码而不是当前(非EDT)线程。并阅读所有摆动组件的Javadoc中出现的警告:http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading