2013-03-05 65 views
0

嗨我试图创建一个gui,它会在每次温度传感器发回信号并更新jlabel值时更新温度。现在我可以通过按更新按钮来更新gui标签,但是我希望它在不按“更新按钮”的情况下自动更新。我尝试了很多方法,包括repaint()revalidate(),并使用不同类型的挥杆定时器,但仍然无法使其工作。有人可以帮我在这里吗?谢谢,我会在底部发布我的代码。在更新温度时更新java中gui的jlabel温度

GUI类:

import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
//import java.util.Timer; 
import javax.swing.*; 

import javax.sound.midi.MidiSystem; 
import javax.sound.midi.MidiUnavailableException; 
import javax.sound.midi.Sequencer; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 


public class gui implements ActionListener{ 

SimpleRead sr = new SimpleRead(); 
// SerialReader serial = new SerialReader(); 
static Sequencer sequencer; 
long position; 

// Definition of global values and items that are part of the GUI 
int desiredTempAmount=74; 
static String roomTempAmount=""; 

//String roomTempAmount=sr.bufferString; 
String ACStatusOnOff ="Off"; 
String ventStatusOpenClose ="Close"; 
boolean automaticOnOff=true; 
boolean openVent=true; 


//String ventStatusAmount = "OPEN"; 

JPanel titlePanel, secondLinePanel, buttonPanel; 
JLabel desiredTempLable, roomTempLabel, desiredTemp; 

JLabel roomTemp; 

JLabel ACstatusLabel; 

JLabel ventStatusLabel; 

JLabel ACstatus; 

JLabel ventStatus; 
JButton incTempButton, decTempButton, resetButton, TurnACOnOffButton, ManaulVentButton; 

public JPanel createContentPane(){ 

    // We create a bottom JPanel to place everything on. 
    JPanel totalGUI = new JPanel(); 
    totalGUI.setLayout(null); 
    //totalGUI.setBounds(500, 500, 500, 200); 

    // Creation of a Panel to contain the title labels 
    titlePanel = new JPanel(); 
    titlePanel.setLayout(null); 
    titlePanel.setLocation(10, 0); 
    titlePanel.setSize(500, 30); 
    totalGUI.add(titlePanel); 

    desiredTempLable = new JLabel("Desired Temp"); 
    desiredTempLable.setLocation(0, 0); 
    desiredTempLable.setSize(120, 30); 
    desiredTempLable.setHorizontalAlignment(0); 
    desiredTempLable.setForeground(Color.red); 
    titlePanel.add(desiredTempLable); 

    roomTempLabel = new JLabel("Room Temp"); 
    roomTempLabel.setLocation(130, 0); 
    roomTempLabel.setSize(120, 30); 
    roomTempLabel.setHorizontalAlignment(0); 
    roomTempLabel.setForeground(Color.blue); 
    titlePanel.add(roomTempLabel); 

    ACstatusLabel = new JLabel("Automatic Mode"); 
    ACstatusLabel.setLocation(260, 0); 
    ACstatusLabel.setSize(120, 30); 
    ACstatusLabel.setHorizontalAlignment(0); 
    ACstatusLabel.setForeground(Color.darkGray); 
    titlePanel.add(ACstatusLabel); 

    ventStatusLabel = new JLabel("Vent Status"); 
    ventStatusLabel.setLocation(390, 0); 
    ventStatusLabel.setSize(120, 30); 
    ventStatusLabel.setHorizontalAlignment(0); 
    ventStatusLabel.setForeground(Color.magenta); 
    titlePanel.add(ventStatusLabel); 

    // Creation of a Panel to contain the score labels. 
    secondLinePanel = new JPanel(); 
    secondLinePanel.setLayout(null); 
    secondLinePanel.setLocation(10, 40); 
    secondLinePanel.setSize(1000, 30); 
    totalGUI.add(secondLinePanel); 

    desiredTemp = new JLabel(""+desiredTempAmount); 
    desiredTemp.setLocation(0, 0); 
    desiredTemp.setSize(120, 30); 
    desiredTemp.setHorizontalAlignment(0); 
    secondLinePanel.add(desiredTemp); 

    roomTemp = new JLabel(""+roomTempAmount); 
    roomTemp.setLocation(120, 0); 
    roomTemp.setSize(150, 30); 
    roomTemp.setHorizontalAlignment(0); 
    secondLinePanel.add(roomTemp); 

    ACstatus = new JLabel(""+ACStatusOnOff); 
    ACstatus.setLocation(260, 0); 
    ACstatus.setSize(120, 30); 
    ACstatus.setHorizontalAlignment(0); 
    secondLinePanel.add(ACstatus); 

    ventStatus = new JLabel(""+ventStatusOpenClose); 
    ventStatus.setLocation(390, 0); 
    ventStatus.setSize(120, 30); 
    ventStatus.setHorizontalAlignment(0); 
    secondLinePanel.add(ventStatus); 

    // Creation of a Panel to contain all the JButtons. 
    buttonPanel = new JPanel(); 
    buttonPanel.setLayout(null); 
    buttonPanel.setLocation(10, 80); 
    buttonPanel.setSize(500, 70); 
    totalGUI.add(buttonPanel); 

    // We create a button and manipulate it using the syntax we have 
    // used before. Now each button has an ActionListener which posts 
    // its action out when the button is pressed. 
    incTempButton = new JButton("Up"); 
    incTempButton.setLocation(0, 0); 
    incTempButton.setSize(60, 30); 
    incTempButton.addActionListener(this); 
    buttonPanel.add(incTempButton); 

    decTempButton = new JButton("Down"); 
    decTempButton.setLocation(65, 0); 
    decTempButton.setSize(70, 30); 
    decTempButton.addActionListener(this); 
    buttonPanel.add(decTempButton); 

    resetButton = new JButton("Update Temp"); 
    resetButton.setLocation(0, 40); 
    resetButton.setSize(500, 30); 
    resetButton.addActionListener(this); 
    buttonPanel.add(resetButton); 

    TurnACOnOffButton = new JButton("Auto On/Off"); 
    TurnACOnOffButton.setLocation(260, 0); 
    TurnACOnOffButton.setSize(120, 30); 
    TurnACOnOffButton.addActionListener(this); 
    buttonPanel.add(TurnACOnOffButton); 

    ManaulVentButton = new JButton("Open/Close"); 
    ManaulVentButton.setLocation(385, 0); 
    ManaulVentButton.setSize(115, 30); 
    ManaulVentButton.addActionListener(this); 
    buttonPanel.add(ManaulVentButton); 

    totalGUI.setOpaque(true); 
    return totalGUI; 
} 

// This is the new ActionPerformed Method. 
// It catches any events with an ActionListener attached. 
// Using an if statement, we can determine which button was pressed 
// and change the appropriate values in our GUI. 

public void update(){ 
    int pause = 1900; 
    System.out.println("updated"); 
    roomTemp.setText("" + sr.buff[1]); 
    Timer t = new Timer(1000, new ActionListener(){ 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // TODO Auto-generated method stub 

      roomTemp.setText("" + sr.buff[1]); 
      roomTemp.repaint(); 
      roomTemp.revalidate(); 
     } 

    }); 
    t.setInitialDelay(pause); 
    t.start(); 
} 

public void actionPerformed(ActionEvent e) { 

    roomTemp.setText("" + sr.buff[1]); 
    if(e.getSource() == incTempButton) 
    { 
     desiredTempAmount = desiredTempAmount + 1; 
     desiredTemp.setText(""+desiredTempAmount); 
    } 
    else if(e.getSource() == decTempButton) 
    { 
     desiredTempAmount = desiredTempAmount - 1; 
     desiredTemp.setText(""+desiredTempAmount); 
    } 
    else if(e.getSource() == resetButton) 
    { 
     //desiredTempAmount = 70; 
     roomTempAmount = sr.bufferString; 
     desiredTemp.setText("" + desiredTempAmount); 
     //roomTemp.setText("" + roomTempAmount); 
//   roomTemp.setText("" + sr.buff[1]); 
    } 
    else if(e.getSource() == TurnACOnOffButton && automaticOnOff==false) 
    { 
     ACStatusOnOff="Off"; 
     ACstatus.setText(""+ACStatusOnOff); 
     automaticOnOff=true; 
    } 


    else if(e.getSource() == TurnACOnOffButton && automaticOnOff == true) 
    { 
     ACStatusOnOff="On"; 
     ACstatus.setText(""+ACStatusOnOff); 
     automaticOnOff=false; 
    } 

    else if(e.getSource() == ManaulVentButton && automaticOnOff == 
           true && openVent==true) 
    { 
     ventStatusOpenClose="Open"; 
     ventStatus.setText(""+ventStatusOpenClose); 
     openVent=false; 
    } 

    else if(e.getSource() == ManaulVentButton && automaticOnOff == 
           true && openVent==false) 
    { 
     ventStatusOpenClose="Close"; 
     ventStatus.setText(""+ventStatusOpenClose); 
     openVent=true; 
    } 
} 



public static void createAndShowGUI() 
{ 
    { 
    JFrame.setDefaultLookAndFeelDecorated(true); 
    JFrame frame = new JFrame("Techficient"); 

    //Create and set up the content pane. 
    gui demo = new gui(); 


    frame.setContentPane(demo.createContentPane()); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(560, 190); 
    frame.setVisible(true); 


} 
} 
} 

序列读取器类:

import gnu.io.CommPort; 

import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort; 
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Arrays; 

import java.applet.Applet; 
//GUI IMPORTS 
import java.awt.*; 
import java.awt.event.*; 

import javax.net.ssl.SSLEngineResult.Status; 
import javax.sound.midi.MidiUnavailableException; 
import javax.swing.*; 

/** 
* This version of the TwoWaySerialComm example makes use of the 
* SerialPortEventListener to avoid polling. 
* 
*/ 
public class SimpleRead 
{ 
OutputStream out; 
SerialReader input; 
static String bufferString; 
static gui newgui = new gui(); 
static String [] buff; 
public SimpleRead() 
{ 
    super(); 
} 

void connect (String portName) throws Exception 
{ 
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); 
    if (portIdentifier.isCurrentlyOwned()) 
    { 
     System.out.println("Error: Port is currently in use"); 
    } 
    else 
    { 
     CommPort commPort = portIdentifier.open(this.getClass().getName(),2000); 

     if (commPort instanceof SerialPort) 
     { 
      SerialPort serialPort = (SerialPort) commPort; 


    serialPort.setSerialPortParams(
    9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); 

      InputStream in = serialPort.getInputStream(); 
      out = serialPort.getOutputStream(); 

      input = new SerialReader(in);     
      serialPort.addEventListener(input); 
      serialPort.notifyOnDataAvailable(true); 
      Thread.sleep(3000); 
     } 
     else 
     { 
      System.out.println("Error: Only serial ports are handled by this code."); 
     } 
    }  
} 

/** 
* Handles the input coming from the serial port. A new line character 
* is treated as the end of a block in this example. 
**/ 
public static class SerialReader implements SerialPortEventListener 
{ 
    private InputStream in; 
    private byte[] buffer = new byte[1024]; 
    String s; 

    public SerialReader (InputStream in) 
    { 
     this.in = in; 
    } 

    public void serialEvent(SerialPortEvent arg0) { 
     int data; 
     String delims="[ B]+"; 
     try 
     { 
      int len = 0; 
      while ((data = in.read()) > -1) 
      { 
       if (data == '\n') { 
        break; 
       } 
       buffer[len++] = (byte) data; 
      } 
      newgui.roomTempAmount="no test"; 
      System.out.println(newgui.roomTempAmount); 
      newgui.roomTempAmount= new String(buffer,0,len);     
      bufferString =newgui.roomTempAmount; 
      buff=newgui.roomTempAmount.split("\\s"); 
      System.out.println(buff[1]); 
      newgui.roomTempAmount=buff[1]; 
      newgui.update(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
      System.exit(-1); 
     }    
    } 
} 


public String getTemp() 
{ 
    try 
    { 
     int sending=newgui.desiredTempAmount; 
     this.out.write(sending); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    try 
    { 
     Thread.sleep(3000); 
    } 
    catch (InterruptedException e) 
    { 
     e.printStackTrace(); 
    } 
    return input.s; 
} 

public static void main (String[] args) throws IOException 
{ 
    SimpleRead sr; 
    //newgui.func(); 
    try 
    { 
     sr = new SimpleRead(); 
     sr.connect("COM5"); 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       newgui.createAndShowGUI(); 
       System.out.println(newgui.roomTempAmount); 
      } 
     }); 
     sr.getTemp(); 
     sr.getTemp(); 
     sr.getTemp(); 
     sr.getTemp(); 
     sr.getTemp(); 
     sr.getTemp(); 
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    
     sr.getTemp();    

     System.out.println(newgui.roomTempAmount); 

    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 
} 

这里是我的GUI的图像,

http://i692.photobucket.com/albums/vv287/kkmoslehpour/guiimage_zps1e26756b.png

这里是我的堆栈跟踪的错误,我不为我的第一个jlabel获得一个空指针,但当我声明它在其他地方b ecomes null(我为roomTemp标签'1'打印一个路径,但'2'为空'3'打印出房间温度,当我添加roomTempAmount时)

1 javax.swing.JLabel [,120 ,0,150x30,无效,alignmentX = 0.0,alignmentY = 0.0,边界=,旗帜= 8388608,MAXIMUMSIZE =,=的minimumSize,首选大小=,=的DefaultIcon,disabledIcon =,的Horizo​​ntalAlignment = CENTER,horizo​​ntalTextPosition = TRAILING,iconTextGap = 4,labelFor = ,文本=,verticalAlignment = CENTER,verticalTextPosition = CENTER] 2空在GUI $ 1 异常在线程 “AWT-EventQueue的-0” 显示java.lang.NullPointerException 。 actionPerfo rmed(gui.java:321) at javax.swing.Timer.fireActionPerformed(Unknown Source) at javax.swing.Timer $ DoPostEvent.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source ) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue $ 3(Unknown Source) at java.awt.EventQueue $ 3.run(Unknown Source) at java.awt.EventQueue $ 3 .run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java。 awt.EventDispatchThread.pumpOneEventForFilters(不明N个源) 在java.awt.EventDispatchThread.pumpEventsForFilter(未知来源) 在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知来源) 在java.awt.EventDispatchThread.pumpEvents(未知来源) 在java.awt.EventDispatchThread。 pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

+0

除了'sleep()',它应该被删除,'SimpleRead'中是否有明显的延迟? – trashgod 2013-03-05 05:37:10

+0

嗨!谢谢你的回复,对于迟到的回复感到抱歉。我在GUI类中添加了更多的sleep(),更新方法。但是你说我应该删除它们,因为它会阻塞事件调度线程? – 2013-03-11 05:41:37

回答

2

Thread.sleep()将阻止event dispatch thread。使用javax.swing.Timer的实例来定期调用您的actionPerformed()方法。

附录:我最初认为你可以轮询从javax.swing.Timer的串行端口,但它看起来像你可能需要使用SwingWorker。在工作人员的构造函数中配置端口,并在工作人员的实现中监听端口; publish()结果,并从process()方法更新您的GUI。有一个相关的例子here

+0

当我尝试对JLabel roomTemp进行引用时,调试程序时,出现空指针异常。所以基本上当我第一次创建roomTemp它可以引用,但是当我在actionPerformed(ActionEvent e)或JPanel createContentPane()之外调用它时update() – 2013-03-11 04:47:36

+0

我得到一个空指针异常对不起,我不熟悉你的串口处理程序,我无法调试你的代码。我已经提出了上面的替代方法。 – trashgod 2013-03-11 07:46:59

+0

trashgod,我上传了一张图片显示我的gui。我只需要温度自己更新,现在它只会更新温度,当我按下更新按钮,这是在我的公共无效actionPerformed(ActionEvent e)方法,roomTemp.setText(“”+ roomTempAmount);//这里是它更新的地方。 – 2013-03-11 09:07:33