嗨,我正在尝试创建一个 gui,每次温度传感器发回信号并更新 jlabel 值时都会更新温度。现在我可以通过按更新按钮来更新 gui 标签,但是我希望它自动更新而不按“更新按钮”。我尝试了很多方法,包括repaint()
, 和revalidate()
, 以及使用不同类型的摇摆计时器,但仍然无法使其正常工作。有人可以帮我吗?谢谢,我将在底部发布我的代码。
图形界面类:
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 获得空指针,但是当我在其他地方声明它时它变为空(我为 roomTemp 标签'1'显示路径,但'2'为空'3'打印当我添加 roomTempAmount 时房间温度)
1 javax.swing.JLabel[,120,0,150x30,无效,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 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(来源不明)