java - JAVA GUI 应用程序中的 jPanel 颜色未改变

标签 java swing arduino jpanel rxtx

我用 Netbeans 制作了一个 JAVA GUI 应用程序。它使用 RXTX 库与 Arduino 进行通信。一切正常。该程序能够从 Arduino 获取串行输出。 arduino 在一秒延迟后重复发送字符串 0 或 1。我编写的程序是这样的:如果它接收到 0,则将 jPanel 着色为红色;如果接收到 1,则将 jPanel 着色为绿色。此外,2 个按钮也使用相同的 jPanel 颜色。但是当运行程序时,当我按下按钮时,它们会按照我想要的方式为 jPanel 着色。但是 0 和 1 上的 if 语句无法为 jPanel 着色。我已经通过放置一些其他语句来检查 if 条件循环工作正常,但仍然无法设置 jPanel 的颜色。 这是我的代码-

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
public class tets extends javax.swing.JFrame implements SerialPortEventListener {
SerialPort serialPort = null;

private static final String PORT_NAMES[] = { 
 //       "/dev/tty.usbmodem", // Mac OS X
//        "/dev/usbdev", // Linux
//        "/dev/tty", // Linux
//      "/dev/serial", // Linux
    "COM3", // Windows
};

private String appName;
private BufferedReader input;
private OutputStream output;
private static final int TIME_OUT = 1000; // Port open timeout
private static final int DATA_RATE = 9600; // Arduino serial port
String inputLine;
public boolean initialize() {
    try {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        // Enumerate system ports and try connecting to Arduino over each
        //
        System.out.println( "Trying:");
        while (portId == null && portEnum.hasMoreElements()) {
            // Iterate through your host computer's serial port IDs
            //
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            System.out.println( "   port" + currPortId.getName() );
            for (String portName : PORT_NAMES) {
                if ( currPortId.getName().equals(portName) 
                  || currPortId.getName().startsWith(portName)) {

                    // Try to connect to the Arduino on this port
                    //
                    // Open serial port
                    serialPort = (SerialPort)currPortId.open(appName, TIME_OUT);
                    portId = currPortId;
                    System.out.println( "Connected on port" + currPortId.getName() );
                    break;
                }
            }
        }

        if (portId == null || serialPort == null) {
            System.out.println("Oops... Could not connect to Arduino");
            return false;
        }

        // set port parameters
        serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

        // add event listeners
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);

        // Give the Arduino some time
        try { Thread.sleep(2000); } catch (InterruptedException ie) {}

        return true;
    }
    catch ( Exception e ) { 
        e.printStackTrace();
    }
    return false;
}



public synchronized void close() {
    if ( serialPort != null ) {
        serialPort.removeEventListener();
        serialPort.close();
    }
}

//
// Handle serial port event
//
public synchronized void serialEvent(SerialPortEvent oEvent) {
    //System.out.println("Event received: " + oEvent.toString());

    try {
        switch (oEvent.getEventType() ) {
            case SerialPortEvent.DATA_AVAILABLE: 
                if ( input == null ) {
                    input = new BufferedReader(
                        new InputStreamReader(
                                serialPort.getInputStream()));
                }
                inputLine = input.readLine();
                System.out.println(inputLine);
                startx(inputLine);
                break;

            default:
                break;
        }

    } 
    catch (Exception e) {
        System.err.println(e.toString());
    }
}
/**
 * Creates new form Parking
 */
public tets() {
    initComponents();
    appName = getClass().getName();
}
/**
 * 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() {

    panel1 = new java.awt.Panel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jTextField2 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
    panel1.setLayout(panel1Layout);
    panel1Layout.setHorizontalGroup(
        panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 250, Short.MAX_VALUE)
    );
    panel1Layout.setVerticalGroup(
        panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 206, Short.MAX_VALUE)
    );

    jButton1.setText("connect");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("jButton2");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jTextField2.setText("jTextField2");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(70, Short.MAX_VALUE)
            .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(80, 80, 80))
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(107, 107, 107)
                    .addComponent(jButton1)
                    .addGap(29, 29, 29)
                    .addComponent(jButton2))
                .addGroup(layout.createSequentialGroup()
                    .addGap(158, 158, 158)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(15, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jButton2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(15, 15, 15)
            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jTextField2.setText("Parked");
        panel1.setBackground(Color.RED);
}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    panel1.setBackground(Color.GREEN);
    jTextField2.setText("Free");            
}                                        

private void startx(String inputLine){
    int a = Integer.parseInt(inputLine);
    Color color;
    if (a == 0){
        color = Color.RED;
        panel1.setBackground(color);
    }
    else{
        color = Color.GREEN;
        panel1.setBackground(color);
    }
    System.out.println(color);
    panel1.repaint();

}
/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
      tets test = new tets();
     if ( test.initialize() ) {
        try { Thread.sleep(2000); } catch (InterruptedException ie) {}
    }
    /* 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(tets.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(tets.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(tets.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(tets.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 tets().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JTextField jTextField2;
private java.awt.Panel panel1;
// End of variables declaration                   
}

提前致谢:)

最佳答案

我认为这可能是由于 EDT 上未处理串行端口事件。 如果将 startx(inputLine) 调用包装在 SwingUtilities.invokeLater() 中会怎样?

    SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                    startx(inputLine);
            }
    });

看看是否有效。

编辑:问题是当您使其可见时,您正在 main 方法中重新创建 tets 实例。因此,初始化的实例甚至没有被使用。使用已经创建的 tets 实例(在 main 方法中将 new tets().setVisible(true); 替换为 test.setVisible(true),您必须将变量 test 更改为 Final。)以及上述建议(稍后使用 invoke),它将起作用。

关于java - JAVA GUI 应用程序中的 jPanel 颜色未改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35503675/

相关文章:

java - 使用并行流从两个字符串中查找匹配字符的第一个索引

c++ - 在类中的 lcd 对象上调用函数

arduino - 如何使用 nRF24L01(+) 2.4GHz 无线收发器查找管道地址

c++ - 命名空间调用的多定义错误

java - 悲观离线锁(Java,Spring)

Java 从文本文件中提取随机值

java - 将空值保存到多对一 hibernate 关系错误

java - 使用java运行风扇

Java 布局管理器建议

java - 如何从 JPanel 类访问 JFrame 组件?