Java中的setText不起作用

时间:2013-10-28 00:38:34

标签: java swing jtextarea

我正在学习Java,我正在尝试做这个settext工作,但我没有得到

public static void main(String args[]) throws Exception
{
    try {
        (new Visual()).connect("COM4", "1");
        (new Visual()).connect("COM6", "2");
    } catch ( Exception e ) {
        e.printStackTrace();
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Visual().setVisible(true);
        }
    });
}
void connect ( String portName, String linha ) 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(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

            status_porta2.setText(portName);
            .....

        }
    }    
}

我正在搜索更改此功能中的标签文字,但无法正常工作..发生了什么? 感谢

1 个答案:

答案 0 :(得分:1)

问题是,您正在创建Visual的多个实例,其中两个用于打开连接,另一个用于显示在屏幕上。

这些都没有任何关联,这意味着屏幕上的内容不是被管理/操纵的内容。

相反,用于连接到端口的实例应该是您显示的实例...

例如......

public static void main(String args[]) throws Exception
{
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Visual v1 = new Visual();
                v1.connect("COM4", "1");
                v1.setVisible(true);

                Visual v2 = new Visual();
                v2.connect("COM6", "2");
                v2.setVisible(true);
            } catch ( Exception e ) {
                e.printStackTrace();
            }
        }
    });
}
相关问题