Java 从外部调用时 Swing 标签未更新 class

Java Swing Label not updating when called from outside class

我正在尝试使用 java swing 中串口的数据更新 JTextBox。我面临的问题是 JTextBox 没有得到更新。 我也尝试了 repaint() 和 revalidate 函数,但没有使用。我还尝试将 setText() 放入可运行对象中。什么都不管用。请指导我。

public class PrinterUI extends javax.swing.JFrame{

/**
 * Creates new form PrinterUI
 */
public PrinterUI() {
    initComponents();
    initOtherUI();
}

public void initOtherUI(){
    menu = new ArrayList<javax.swing.JMenuItem>();
}

public void showSensorValueOnScreen(long id, int pres, int temp){
    System.out.println(Long.toHexString(id));
    sensorID = id;
    System.out.println(Long.toHexString(sensorID));
    
    opText.setText(Long.toHexString(sensorID));
}



/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jMenu3 = new javax.swing.JMenu();
    jButton1 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    opText = new javax.swing.JTextField();
    jMenuBar1 = new javax.swing.JMenuBar();
    printerMenuBar = new javax.swing.JMenu();
    mobileMenuBar = new javax.swing.JMenu();

    jMenu3.setText("jMenu3");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("Print");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton1MouseClicked(evt);
        }
    });

    jLabel1.setText("Sensor Output");

    opText.setText("jTextField1");
    opText.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            opTextPropertyChange(evt);
        }
    });

    printerMenuBar.setText("Printer");
    printerMenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            printerMenuBarMouseClicked(evt);
        }
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            printerMenuBarMouseEntered(evt);
        }
    });
    jMenuBar1.add(printerMenuBar);

    mobileMenuBar.setText("Mobile");
    jMenuBar1.add(mobileMenuBar);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(203, 203, 203)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1)
                .addComponent(jButton1))
            .addContainerGap(236, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(108, Short.MAX_VALUE)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(52, 52, 52)
            .addComponent(jButton1)
            .addGap(105, 105, 105))
    );

    getAccessibleContext().setAccessibleName("jLabel1");

    pack();
}// </editor-fold>                        

private void printerMenuBarMouseClicked(java.awt.event.MouseEvent evt) {                                            
    System.out.println("clicked");
}                                           

private void printerMenuBarMouseEntered(java.awt.event.MouseEvent evt) {                                            
    String[] portNames = null;
    portNames = SerialPortList.getPortNames();
    for (String string : portNames) {
        System.out.println(string);
    }
    
    if (portNames.length == 0) {
        System.out.println("There are no serial-ports");
    } else {

        SerialPort serialPort = new SerialPort("COM25");
        try {
            serialPort.openPort();

            serialPort.setParams(SerialPort.BAUDRATE_9600,    SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);

            PortReader portReader = new PortReader(serialPort);

            serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);
        } catch (Exception e) {
            System.out.println("There are an error on writing string to port т: " + e);
        }
    }
     
     
}                                           

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
    // TODO add your handling code here:
    System.out.println("Print Click");
    opText.setText(Long.toString(sensorID));
    System.out.println(Long.toHexString(sensorID));        
}                                     
                                

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new PrinterUI().setVisible(true);
        }
    });
}

private List<javax.swing.JMenuItem> menu;
PrintService pservice = null;
public static long sensorID;


// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu mobileMenuBar;
private javax.swing.JTextField opText;
private javax.swing.JMenu printerMenuBar;
// End of variables declaration         

      

}

class PortReader implements SerialPortEventListener{

SerialPort serialPort;
public int[] incomingData = new int[20];
public int dataIndex=0;
public long sensorID=0;
public int pressure;
public int temperature;

public PortReader(SerialPort serialPort) {
    this.serialPort = serialPort;
}

@Override
public void serialEvent(SerialPortEvent event) {
    if (event.isRXCHAR() && event.getEventValue() > 0) {
        try {
            String receivedData = serialPort.readHexString();
            
            for(int x=0;x<receivedData.length();x=x+2){
                int data = Integer.parseInt(receivedData.substring(x, x+2),16);
                //System.out.println(data);
                if((dataIndex==0)&&(data==170)){
                    incomingData[dataIndex++]=data;
                }else if(dataIndex>0){
                    incomingData[dataIndex++]=data;
                    if(dataIndex>=14){   
                        dataIndex=0;
                        long tyreId =(long)(((int)incomingData[6])*16777216 + ((int)incomingData[7])*65536 + ((int)incomingData[8])*256 + ((int)incomingData[9]));
                        tyreId = tyreId & 0x00000000FFFFFFFFL;
                        int press = incomingData[10];
                        int temp = incomingData[11];
                        sensorID = tyreId;
                        pressure = press;
                        temperature = temp;
                        
                        PrinterUI obj = new PrinterUI();
                        obj.showSensorValueOnScreen(sensorID, pressure, temperature);
                        
                        System.out.println("ID: " + Long.toHexString(tyreId) + ", Pressure: " + pressure + ", Temperature: " + temperature);
                    }
                }else{
                    dataIndex=0;
                }
            }
        } catch (SerialPortException ex) {
            System.out.println("Error in receiving string from COM-port: " + ex);
        }
    }
}

}

当接收到串行数据时,在 PortReader class 中调用 serialEvent,后者又在 PrinterUI class 中调用 showSensorValueOnScreen() 方法。 JTextBox 小部件未更新。

但是当按下 UI 上的按钮时,JTextBox 会更新。

为什么当我从 class 外部调用它时它没有得到更新?。请帮帮我。

我发现了问题。我正在尝试通过为 UI 创建一个新对象来从另一个 class 更新 UI。实际的 UI 是使用不同的对象从 void main 创建的。

我通过将现有对象传递给调用 UI 更新函数的 class 来解决它。

谢谢大家的帮助。