jPanel颜色在JAVA GUI应用程序中不变

时间:2016-02-19 10:59:47

标签: java swing arduino jpanel rxtx

我使用Netbeans制作了一个JAVA GUI应用程序。它使用RXTX库与Arduino进行通信。一切正常。该程序能够从Arduino获得串行输出。 arduino在一秒延迟后重复发送字符串0或1。我制作程序,如果它收到0,它将jPanel颜色为红色,如果它变为1,它将jPanel颜色为绿色。此外,2个按钮也为同一jPanel着色。但是当运行程序时,当我按下按钮时,它们会根据需要为jPanel着色。但0&的if语句1无法为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                   
}

提前致谢:)

1 个答案:

答案 0 :(得分:0)

我认为这可能是由于EDT上没有处理串口事件。 如果在SwingUtilities.invokeLater()中包装startx(inputLine)调用该怎么办。

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

看看是否有效。

编辑:问题是当您使主要方法可见时,您正在重新创建主要方法的实例。因此,甚至没有使用初始化的实例。使用已创建的tets实例(将 new tets()。setVisible(true); 更改为main方法中的 test.setVisible(true),您将不得不更改变量测试是最终的。)以及上面的建议(稍后使用调用),它将起作用。