当前位置: 首页 > 知识库问答 >
问题:

当温度更新时,在java的gui上更新jlabel温度

凌通
2023-03-14

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

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

这是我的stacktrace错误,我没有为我的第一个jlabel得到一个空指针,但当我在其他地方声明它时,它变为空(我为roomTemp标签“1”做了一个println,显示一个路径,但“2”为空“3”在我添加roomTempAmount时打印出房间温度)

1 javax。摆动JLabel[,120,0150x30,无效,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=中心,horizontalTextPosition=尾随,iconTextGap=4,labelFor=,text=,verticalAlignment=中心,verticalTextPosition=中心]1 66

72 2 null 3 72异常在线程"AWT-EventQuue-0"1.doNullPointerException at gui$java.awt.执行(ueue.dispatch)在java.awt.Thread.pumpActionPerform(未知源)在java.awt.Timer$DoPostEhread.pump(未知源)在java.awt.InvocationEhread.pump(未知源)在java.awt.EventQhread.pumpEventImpl(未知源)在java.awt.EventQueue.access200美元(未知源)在java.awt.EventQueue$3.run(未知源)在java.awt.EventQueue$3.run(未知源)在java.security.AccessController.doPrivileged(Native Method)在java.security.保护域$java.lang.IntersectionPrivilge(未知源)在1.actionEventQgui.java:321事件(未知源)在javax.swing.EventDispatchTimer.fireOneEventForFilters(未知源)在javax.swing.EventDispatchTvent.runEventsForFilter(未知源)在java.awt.event.EventDispatchTvent.dispatchEventsForHi等级(未知源)在java.awt.EventDispatchTueue.dispatch事件(未知源)

共有1个答案

燕富
2023-03-14

线程。sleep()将阻止事件调度线程。使用javax的实例。摆动计时器定期调用actionPerformed()方法。

附录:我最初认为您可以从javax.swing.Timer轮询串行端口,但看起来您可能需要使用SwingWorker。在工作器的构造函数中配置端口,并在工作器的doInbackground()实现中监听端口;发布()结果,并从进程()方法更新您的GUI。这里有一个相关的示例。

 类似资料:
  • Python3 实例 以下实例演示了如何将摄氏温度转华氏温度:# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.runoob.com # 用户输入摄氏温度 # 接收用户输入 celsius = float(input('输入摄氏温度: ')) # 计算华氏温度 fahrenheit = (celsius * 1.8) +

  • 我在Java从华氏温度转换到摄氏温度时遇到了问题。我刚刚开始学习Java,现在还在阅读书籍和教程。 对于我的第一个程序,我正在尝试根据本教程创建一个基本的温度计算器。 我想扩展它的功能,也包括华氏温度到摄氏温度的转换,以及基本摄氏温度到华氏温度的转换。 因此,我使用给出的示例代码完成了摄氏温度到华氏温度的部分,现在,使用相同的代码,经过大量的试验和错误后稍微修改,我正在尝试处理另一半。我让它在某种

  • 我是一个Java GUI初学者,在让我的面板按照我想要的方式进行更新方面遇到了一些麻烦。基本上,当用户点击我的GUI中的一个按钮时,屏幕上当前的形状应该改变为与按钮按下对应的任何形状。我的代码在下面。更新后的形状在显示前被原始形状覆盖的问题。 最后,这里是我的框架类: 谢谢你的帮助!

  • 温度控制 [HW,ACPI] thermal.act=摄氏度 -1 禁用所有"主动散热"标志点(active trip point) 正整数 强制设置所有的最低"主动散热"标志点的温度值,单位是摄氏度。 详见Documentation/thermal/sysfs-api.txt文档。 [HW,ACPI] thermal.psv=摄氏度 -1 禁用所有"被动散热"标志点(passive trip p

  • 我对Java还是个新手,在理解OOP方面更是新手,所以请不要取笑我的不理解。 我试图设计一个程序,让用户输入华氏或摄氏度的温度,然后程序将确定另一个测量中的温度。 有没有人能给我一些建议,告诉我我的方向是否正确? 这是我到目前为止所做的,请记住,这是我对OOP的第一次尝试,所以它可能看起来一团糟。

  • 我在Cooja上读不到不同的温度读数。我做了以下工作: 创建了一个初始化灯光和温度传感器的源文件 使用天空微尘创建了模拟 使用8个微尘网络运行模拟 每个微尘的读数都是相同的温度,这对我想要的东西是无用的。在过去的8个小时里,我一直在浏览线程、文档(包括Contiki wiki),但没有找到任何东西。 如果我误解了Cooja/Contiki的工作方式,我也希望得到一些帮助,但是,底线是,我如何模拟模