更新温度时在Java中的gui上更新jlabel温度 [英] Updating jlabel temperature on the gui in java when temperature is updated

查看:65
本文介绍了更新温度时在Java中的gui上更新jlabel温度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个gui,它将在每次温度传感器发送回信号并更新jlabel值时更新温度.现在,我可以通过按更新按钮来更新gui标签,但是我希望它可以自动更新而无需按更新按钮".我尝试了很多方法,包括repaint()revalidate(),并且使用了不同类型的摆动计时器,但仍然无法使它正常工作.有人可以帮我吗?谢谢,我会将我的代码发布在底部.

Hi I am trying to create a gui that will update the temperature every time the temperature sensor sends back a signal and update the jlabel value. Right now I am able to update the gui label by pressing the update button, however i want it to update automatically without pressing the "update button". I have tried a lot of method including repaint(), and revalidate(), and using different type of swing timers but still cannot get it to work. Can someone please help me out here? Thanks I will post my code on the bottom.

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();
    }
}
}

这是我的图形用户界面的图片,

here is the image of my gui,

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

这是我的stacktrace错误,我没有为我的第一个jlabel得到一个nullpointer,但是当我声明它为null的其他地方时(我为roomTemp Label'1'做一个println显示路径,但是'2'为null'当我添加roomTempAmount时,3'打印出室温

here is my stacktrace error, i dont get a nullpointer for my first jlabel but when i declare it else where it becomes null (i do a println for roomTemp Label '1' show a path, but '2' is null '3' prints out the room temp when i add the roomTempAmount)

1 javax.swing.JLabel [,120,0,150x30,invalid,alignmentX = 0.0,alignmentY = 0.0,border =,flags = 8388608,maximumSize =,minimumSize =,preferredSize =,defaultIcon =,disabledIcon =,horizo​​ntalAlignment = CENTER,horizo​​ntalTextPosition = TRAILING,iconTextGap = 4,labelFor =,text =,verticalAlignment = CENTER,verticalTextPosition = CENTER] 1个 66 72 66

1 javax.swing.JLabel[,120,0,150x30,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=CENTER,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,verticalTextPosition=CENTER] 1 66 72 66

72 2 null 3 72 线程"AWT-EventQueue-0"中的异常java.lang.NullPointerException 在gui $ 1.actionPerformed(gui.java:321) 在javax.swing.Timer.fireActionPerformed(未知来源) 在javax.swing.Timer $ DoPostEvent.run中(未知源) 在java.awt.event.InvocationEvent.dispatch(未知来源) 在java.awt.EventQueue.dispatchEventImpl(未知源) 在java.awt.EventQueue.access $ 200(未知源) 在java.awt.EventQueue $ 3.run(未知源) 在java.awt.EventQueue $ 3.run(未知源) 在java.security.AccessController.doPrivileged(本机方法) 在java.security.ProtectionDomain $ 1.doIntersectionPrivilege(未知来源) 在java.awt.EventQueue.dispatchEvent(未知来源) 在java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源) 在java.awt.EventDispatchThread.pumpEventsForFilter(未知来源) 在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知来源) 在java.awt.EventDispatchThread.pumpEvents(未知来源) 在java.awt.EventDispatchThread.pumpEvents(未知来源) 在java.awt.EventDispatchThread.run(未知来源)

72 2 null 3 72 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at gui$1.actionPerformed(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.access$200(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(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

推荐答案

Thread.sleep()将阻止事件分配线程.使用 javax.swing.Timer 的实例定期调用您的actionPerformed()方法.

Thread.sleep() will block the event dispatch thread. Use an instance of javax.swing.Timer to periodically invoke your actionPerformed() method.

附录:我最初以为您可以从javax.swing.Timer轮询串行端口,但是看来您可能需要使用SwingWorker.在工作程序的构造函数中配置端口,并在工作程序的doInBackground()实现中侦听该端口; publish()到达时会生成结果,并通过process()方法更新您的GUI. 此处.

Addendum: I initially thought you could poll the serial port from a javax.swing.Timer, but it looks like you may need to use a SwingWorker. Configure the port in the worker's constructor, and listen to the port in the worker's doInBackground() implementation; publish() results as they arrive, and update your GUI from the process() method. There's a related example here.

这篇关于更新温度时在Java中的gui上更新jlabel温度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆