2013-03-09 46 views
0

我正在通过串行通信进行实时图形绘制。我有数据进来称为我的“摄氏”值。我在JLabel的GUI中显示,所以值不断变化。我遇到的问题是我想要具有可以将JLabel中的值更改为华氏度或返回摄氏度的按钮。所以现在,我有我的actionPerformed调用updateTemp()方法,以便在程序存在时立即更新JLabel。我认为下面的代码是我认为需要改变的3种方法。在实时绘图中使用不同的值更新JLabel

public void actionPerformed(final ActionEvent e) { 
    updateTempC(); 
    final Double n = serial.x; 
    series.addOrUpdate(new Millisecond(), n); 
    Object source = e.getSource(); 

    if (e.getSource() == buttonF){ 
    degree.setText("degrees F"); 
    updateTempF(); 
    } 

    if (e.getSource() == buttonC){ 
    degree.setText("degrees C"); 
    updateTempC(); 
    } 
} 

public void updateTempF(){ 
    int step1; 
    int step2; 
    int step3; 
    String indata = serial.temp; 
    int temp = Integer.parseInt(indata); 
    step1 = temp*9; 
    step2 = step1/5; 
    step3 = step2 + 32; 
    String indata1 = Integer.toString(step3); 
    this.realtime.setText(indata1); 
} 

public void updateTempC(){ 
    String indata = serial.temp; 
    this.realtime.setText(indata); 
} 

现在当我按下一个JButton更改为华氏,它改变了第二但是随后右后卫,因为图形每秒更新一次和的actionPerformed会马上回调用updateTempC显示摄氏度()。我想知道,当我按下Fahr的按钮时。或Cels。,它会在其余时间改变。 THanks

+0

请编辑您的帖子上方并重新发布格式正确的代码。阅读和理解所有左对齐的代码是非常困难的。如果您要求我们尽力帮助您,请尽量不要让您的问题比应该更难。解决方案背后的逻辑是没有将数据显示代码设置为JLabel,而只是让按钮更改JLabel。 – 2013-03-09 23:01:34

+0

当新数据从串口被调用时调用'actionPerformed()',称为是按钮,还是称为'JButtons'的_only_? – 2013-03-09 23:46:45

+0

@Java,我有actionPerformed()被调用,当新的数据来的时候以及由按钮调用的那一刻。 – Patrick 2013-03-10 02:07:53

回答

1

你应该有一个像boolean fahrenheitTemp这样的变量。当点击buttonF时,fahrenheitTemp将被设置为true。当点击buttonC时,fahrenheitTemp将被设置为false。如果fahrenheitTemptrue,请致电updateTempF(),否则请致电updateTempC()。 (另外,你有一个Object source变量,但你永远不使用它。)

尝试修改您的actionPerformed(ActionEvent)到这样的事情:

boolean fahrenheitTemp = false; 
public void actionPerformed(final ActionEvent e) { 
    if (fahrenheitTemp) { 
     updateTempF(); 
    } else { 
     updateTempC(); 
    } 
    final Double n = serial.x; 
    series.addOrUpdate(new Millisecond(), n); 
    Object source = e.getSource(); 
    if (source == buttonF) { 
     degree.setText("degrees F"); 
     fahrenheitTemp = true; 
     updateTempF(); 
    } else if (source == buttonC) { 
     degree.setText("degrees C"); 
     fahrenheitTemp = false; 
     updateTempC(); 
    } 
} 
+0

感谢@ Java的回应。它效果很好。谢谢你帮我弄清楚这是非常烦人的,而且似乎很简单,以解决这个问题,我无法将我的头围绕它。也感谢您让我知道该对象源变量。欢呼声 – Patrick 2013-03-10 18:26:37

+1

@Patrick不客气。我很高兴它帮助:) – 2013-03-10 20:19:46