Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: interaction between serial rxtx and swing

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default interaction between serial rxtx and swing

    Hi I'm a beginner in java, I'm trying to make a simple program to show available serial ports in a Jmenu
    I have separate classes:

    - the serialCommunication class
    - the gui class
    - the main class

    the serialCommunication class contains the method getAvailablePorts(), so If I call it from the main class, I get the com ports list and it works
    the gui class contains the methods to build the jframe and the jmenu, so when I call the method gui.build() from the main class everything works fine


    now, I'd like to list the available serial ports in a Jmenu, and have the ports list rescanned every time the menu is opened but I can't call the method getAvailablePorts() from the gui class because I get an error "cannot make a static reference to the non static method..."
    I think this is because the serial port instance exists only in the main class, so I can't call its methods from another class.
    Could you please point me in the right direction...


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: interaction between serial rxtx and swing

    "cannot make a static reference to the non static method..."
    You should move most of the code out of the main() method into a non static method in the class.
    Have the main() method only call the class's constructor.

    If this is not it, post the code with the error and the full text of the error message that shows where the error is occurring.

    You need an instance of a class to call any of its non-static methods from a static method in the class:
    refToClass.aMethod();
    From a non-static method there is the this (the default) reference:
    this.aMethod();
    Last edited by Norm; September 8th, 2012 at 04:34 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: interaction between serial rxtx and swing

    here is the whole serial communication class:


    import gnu.io.CommPort;
    import gnu.io.CommPortIdentifier;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import java.util.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Enumeration;
     
     
     
    public class SerialCommunication implements SerialPortEventListener 
    {
     
    	  InputStream input;
    	  OutputStream output;
    	  CommPort commPort;
    	  byte buffer[] = new byte[32768];
    	  int bufferIndex;
    	  int bufferLast;
    	  public int[] dataIn = new int[20];
    	  public byte[] dataOut = new byte [90];
    	  int counter = 0;
    	  int rate;
    	  int parity;
    	  int databits;
    	  int stopbits;
    	  boolean monitor = true;
    	  MessageConsumer consumer;
     
    	  boolean Reply1Received = false;
    	  boolean Reply2Received = false;
    	  boolean Reply3Received = false;
    	  boolean Reply4Received = false;
    	  boolean Reply5Received = false;
    	  boolean _allowed = false;
    		byte[] _key = new byte[2];
    		int _verifyCount = 0;
    		int _serialCount = 0;
    		byte[] _inBuffer = new byte[6];
    		int _checkSum = 0;
     
    		byte InByte1 = 0;
    		byte InByte2 = 0;
    		byte InByte3 = 0;
    		byte InByte4 = 0;
     
    		byte[] reply1 = new byte[4];
    		byte[] reply2 = new byte[4];
    		byte[] reply3 = new byte[4];
    		byte[] reply4 = new byte[4];
    		byte[] reply5 = new byte[4];
     
        public SerialCommunication()
        {
            super();
        }
     
        void connect ( String portName ) throws Exception
     
        {        _key[0] = 1;
    	         _key[1] = -2;
     
     
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            if ( portIdentifier.isCurrentlyOwned() )
            {
                System.out.println("Error: Port is currently in use");
            }
            else
            {
                 commPort = portIdentifier.open(this.getClass().getName(),1000);
     
                if ( commPort instanceof SerialPort )
                {
                    SerialPort serialPort = (SerialPort) commPort;
                    serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
     
     
                    input = serialPort.getInputStream();
        			output = serialPort.getOutputStream();
     
     
     
        			serialPort.addEventListener(this);
        			serialPort.notifyOnDataAvailable(true);
     
                }
                else
                {
                    System.out.println("Error: Only serial ports are handled");
                }  
            }     
        }
        public void addListener(MessageConsumer consumer) {
            this.consumer = consumer;
          }
        public void dispose(){
        	try{
        		if (input != null) input.close();
        		if (output != null) output.close();
        	}
        	catch
        		(Exception e){e.printStackTrace();
     
        			}
        	try{
        		if (commPort != null) commPort.close();
        		}
        	catch (Exception e)
        	{e.printStackTrace();
     
    		}
     
     
        }
     
     
     
        synchronized public void serialEvent(SerialPortEvent serialEvent) {
     
     
            if (serialEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
     
              try {
                while (input.available() > 0) {
     
                  synchronized (buffer) {
                    if (bufferLast == buffer.length) {
                      byte temp[] = new byte[bufferLast << 1];
                      System.arraycopy(buffer, 0, temp, 0, bufferLast);
                      buffer = temp;
                    }
     
     
                    int inByte = input.read();
                    feed(inByte);
                    //System.out.println(inByte);  // uncomment for testing
     
           if (this.consumer != null)
                      this.consumer.message("" + (char) input.read());
     
     
                  }
                }
     
     
              } catch (IOException e) {
     
                System.out.println("no!");
              }
              catch (Exception e) {
              }
            }}
     
     
     
     
        public int read() {
            if (bufferIndex == bufferLast) return -1;
     
            synchronized (buffer) {
              int outgoing = buffer[bufferIndex++] & 0xff;
              if (bufferIndex == bufferLast) {  // rewind
                bufferIndex = 0;
                bufferLast = 0;
              }
              return outgoing;
            }
          }
     
        public char readChar() {
            if (bufferIndex == bufferLast) return (char)(-1);
            return (char) read();
          }
     
        public void write(int what) { 
            try {
              output.write(what & 0xff);  
              output.flush();  
     
            } catch (Exception e) { // null pointer or serial port dead
              //errorMessage("write", e);
            }
          }
     
     
          public void write(byte bytes[]) {
            try {
              output.write(bytes);
              output.flush();   
     
            } catch (Exception e) { 
              e.printStackTrace();
            }
          }
     
        /** */
       /* public static class SerialWriter implements Runnable 
        {
            OutputStream out;
     
            public SerialWriter ( OutputStream out )
            {
                this.out = out;
            }
     
            public void run ()
            {
                try
                {                
                    int c = 0;
                    while ( ( c = System.in.read()) > -1 )
                    {
                        this.out.write(c);
                    }                
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                    System.exit(-1);
                }            
            }
        }*/
     
        public List<String> getAvailablePorts() {
     
    	    List<String> list = new ArrayList<String>();
     
    	    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
     
    	    while (portList.hasMoreElements()) {
    	        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
    	        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    	            list.add(portId.getName());
    	        }
    	    }
     
    	    return list;
    	}
     
    void feed(int _inByte){
     
     
     
    		if(_allowed == false){
    			if(_inByte == _key[_verifyCount]){
    			  _verifyCount++;
    			if(_verifyCount > 1){_allowed = true;_verifyCount = 0;}
    			}else{_verifyCount = 0;}} 
     
    			else{_inBuffer[_serialCount] = (byte)_inByte; 
    			     if(_serialCount < 5){
    			     _checkSum += _inByte; }
    			     _serialCount++;
    			    if(_serialCount > 5){
    			         if(_inBuffer[5] == _checkSum){_Process(_inBuffer);}
    			         else{_BadSerialEvent();}
    			             _allowed = false;
    			           _checkSum = 0;
    			         _serialCount = 0;}}
     
     
     
     
     
     
     
    	}
     
     
     
    	void _Process(byte[] _input ){
     
    		 InByte1 = _input[1];
    		 InByte2 = _input[2];
    		 InByte3 = _input[3];
    		 InByte4 = _input[4];
     
     
    	switch (_input[0]){
    	    case 0:
    	        _SaveReply1(InByte1,InByte2,InByte3,InByte4);
    		    Reply1Received = true;
    	    break;
     
    	    case 1:
    	    	_SaveReply2(InByte1,InByte2,InByte3,InByte4);
    	    	Reply2Received = true;
     
    		break;
     
    		case 2:
    			_SaveReply3(InByte1,InByte2,InByte3,InByte4);
    			Reply3Received = true;
    		break;
     
    		case 3:
    			_SaveReply4(InByte1,InByte2,InByte3,InByte4);
    			Reply4Received = true;
    		break;
     
    		case 4:
    			_SaveReply5(InByte1,InByte2,InByte3,InByte4);
    			Reply5Received = true;
    		break;
     
    	}
     
    	}
     
     
     
    	void _BadSerialEvent(){
     
     
     
     
     
     
     
    	}
     
     
    	public void SendFunction1(int byte1, int byte2, int byte3, int byte4){
     
    		//create _checksum
    		_checkSum =   byte1 +  byte2 + byte3 + byte4;
     
    		write(_key);
    		write(0);
    		write((byte)byte1);
    		write((byte)byte2);
    		write((byte)byte3);
    		write((byte)byte4);
    		write((byte)_checkSum);
    		//System.out.println((byte)_checkSum);
    	}
     
    	public void SendFunction2(int byte1, int byte2, int byte3, int byte4){
     
    		_checkSum =  byte1 + byte2 + byte3 + byte4;
     
    		write(_key);
    		write(1);
    		write((byte)byte1);
    		write((byte)byte2);
    		write((byte)byte3);
    		write((byte)byte4);
    		write(_checkSum);
     
    	}
     
    	public void SendFunction3(int byte1, int byte2, int byte3, int byte4){
     
    		_checkSum =  byte1 + byte2 + byte3 + byte4;
     
    		write(_key);
    		write(2);
    		write((byte)byte1);
    		write((byte)byte2);
    		write((byte)byte3);
    		write((byte)byte4);
    		write(_checkSum);
     
    	}
     
    	public void SendFunction4(int byte1, int byte2, int byte3, int byte4){
     
    		_checkSum =  byte1 + byte2 + byte3 + byte4;
     
    		write(_key);
    		write(3);
    		write((byte)byte1);
    		write((byte)byte2);
    		write((byte)byte3);
    		write((byte)byte4);
    		write(_checkSum);
     
    	}
     
    	public void SendFunction5(int byte1, int byte2, int byte3, int byte4){
     
    		_checkSum =  byte1 + byte2 + byte3 + byte4;
     
    		write(_key);
    		write(4);
    		write((byte)byte1);
    		write((byte)byte2);
    		write((byte)byte3);
    		write((byte)byte4);
    		write(_checkSum);
    	}
     
     
     
    	void _SaveReply1(byte byte1, byte byte2, byte byte3, byte byte4){
     
    		reply1[0] = byte1;
    		reply1[1] = byte2;
    		reply1[2] = byte3;
    		reply1[3] = byte4;
     
    	}
     
        void _SaveReply2(byte byte1, byte byte2, byte byte3, byte byte4){
     
        	reply2[0] = byte1;
    		reply2[1] = byte2;
    		reply2[2] = byte3;
    		reply2[3] = byte4;
     
    	}
     
        void _SaveReply3(byte byte1, byte byte2, byte byte3, byte byte4){
     
        	reply3[0] = byte1;
    		reply3[1] = byte2;
    		reply3[2] = byte3;
    		reply3[3] = byte4;
     
        }
     
        void _SaveReply4(byte byte1, byte byte2, byte byte3, byte byte4){
     
        	reply4[0] = byte1;
    		reply4[1] = byte2;
    		reply4[2] = byte3;
    		reply4[3] = byte4;
     
        }
     
        void _SaveReply5(byte byte1, byte byte2, byte byte3, byte byte4){
     
        	reply5[0] = byte1;
    		reply5[1] = byte2;
    		reply5[2] = byte3;
    		reply5[3] = byte4;
     
        }
     
    public void AskDataSet1(int byte1, int byte2, int byte3, int byte4){
     
    		//create _checksum
    		_checkSum =   byte1 +  byte2 + byte3 + byte4;
     
    		write(_key);
    		write(5);
    		write((byte)byte1);
    		write((byte)byte2);
    		write((byte)byte3);
    		write((byte)byte4);
    		write((byte)_checkSum);
    		Reply1Received = false;
    		//System.out.println((byte)_checkSum);
     
    	}
     
    public void AskDataSet2(int byte1, int byte2, int byte3, int byte4){
     
    	//create _checksum
    	_checkSum =   byte1 +  byte2 + byte3 + byte4;
     
    	write(_key);
    	write(6);
    	write((byte)byte1);
    	write((byte)byte2);
    	write((byte)byte3);
    	write((byte)byte4);
    	write((byte)_checkSum);
    	Reply2Received = false;
    	//System.out.println((byte)_checkSum);
     
    }
     
    public void AskDataSet3(int byte1, int byte2, int byte3, int byte4){
     
    	//create _checksum
    	_checkSum =   byte1 +  byte2 + byte3 + byte4;
     
    	write(_key);
    	write(7);
    	write((byte)byte1);
    	write((byte)byte2);
    	write((byte)byte3);
    	write((byte)byte4);
    	write((byte)_checkSum);
    	Reply3Received = false;
    	//System.out.println((byte)_checkSum);
     
    }
     
    public void AskDataSet4(int byte1, int byte2, int byte3, int byte4){
     
    	//create _checksum
    	_checkSum =   byte1 +  byte2 + byte3 + byte4;
     
    	write(_key);
    	write(8);
    	write((byte)byte1);
    	write((byte)byte2);
    	write((byte)byte3);
    	write((byte)byte4);
    	write((byte)_checkSum);
    	Reply4Received = false;
    	//System.out.println((byte)_checkSum);
     
    }
     
    public void AskDataSet5(int byte1, int byte2, int byte3, int byte4){
     
    	//create _checksum
    	_checkSum =   byte1 +  byte2 + byte3 + byte4;
     
    	write(_key);
    	write(9);
    	write((byte)byte1);
    	write((byte)byte2);
    	write((byte)byte3);
    	write((byte)byte4);
    	write((byte)_checkSum);
    	Reply5Received = false;
    	//System.out.println((byte)_checkSum);
     
    }
     
    }

    and here is the gui builder class :

     
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import eu.hansolo.steelseries.gauges.*;
    import org.*;
     
     
    public class guiPanel {
     
     
     
    JPanel mainPanel;
    ArrayList<JTextField> textFieldList;
    JFrame theFrame;
    ArrayList<JLabel> rpmLabels;
    ArrayList<JLabel> tpsLabels;
    ArrayList<JRadioButtonMenuItem> comRadioButtons;
    int rpmMax = 0;
    int tpsMax = 0;
     
    JMenuBar menuBar;
    JMenu serialMenu, submenu;
     
    ArrayList<String> comPortsList;
     
    ActionListener serialMenuListener;
     
     
     
     
     
     
     
    public void refreshComPorts(Object[] comPortsObj){
     
    	comPortsList = new ArrayList<String>();
    	comRadioButtons = new ArrayList<JRadioButtonMenuItem>();
    	ButtonGroup group = new ButtonGroup();
    //	System.out.println(port.getAvailablePorts());
    	if(comPortsObj != null){
    for (int i = 0; i < comPortsObj.length; i++){
    	comPortsList.add((String)comPortsObj[i]);
     
    	JRadioButtonMenuItem e = new JRadioButtonMenuItem(comPortsList.get(i));
    	comRadioButtons.add(e);
    	//group.add(e);
    	serialMenu.add(e);
    }
     
    	//JMenuItem comList = new JMenuItem("Com Port");
    	//item.addActionListener(actionListener);
     
     
     
     
     
    //System.out.println(comPortsList);
    	}
     
     
     
     
     
    }
     
     
     
     
     
    public void buildGui() {
     
    	/******************************************************set look and feel***********************************************/
     
    	try {
    	      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    	    } catch(Exception e) {
    	      System.out.println("Error setting native LAF: " + e);
    	    }
     
     
     
     
     
    	theFrame = new JFrame("Injection Manager");                               //create main window
    	theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                  //close operation setup
    	BorderLayout layout = new BorderLayout();                                 //create border layout used in background jpanel
    	JPanel background = new JPanel(layout);                                   //create background jpanel
    	background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));       //set background borders distance from the main window borders
     
     
    	textFieldList = new ArrayList<JTextField>();                              //arraylist of textfields for the table values
    	rpmLabels = new ArrayList<JLabel>();                                      //arraylist of Jlabels for rpm grid steps
    	tpsLabels = new ArrayList<JLabel>();                                      //arraylist of jlabels for tps grid steps
     
    	theFrame.getContentPane().add(background);                                //put the background jpanel over the main window theFrame
    	GridLayout grid = new GridLayout(13,13);                                    //create grid layout to organize the textfields
    	grid.setVgap(8);                                                          //set the distance top - bottom of the cells
    	grid.setHgap(8);                                                          //set the distance right - left of the cells
    	mainPanel = new JPanel(grid);                                             //create mainpanel, a new jpanel with the grid layout
    	background.add(BorderLayout.CENTER, mainPanel);                           //add mainpanel to background jpanel in the center position
     
    	rpmMax = 8000;
    	tpsMax = 930;
     
     
    /***************************************************************************text fields***********************************************/	
     
    	for(int f = 11;f >= 0; f --){
    		String labelTpsVal = Integer.toString(tpsMax / 11 * f) ;	
    		//System.out.println(labelTpsVal);	
    		JLabel TpsLab = new JLabel(labelTpsVal);
    		tpsLabels.add(TpsLab);
    		mainPanel.add(TpsLab);
     
    		for (int i = 0; i < 12; i++){
    			JTextField t = new JTextField(2);
    			textFieldList.add(t);
    			mainPanel.add(t);
    		}
    		}
     
     
    	//JLabel emptyLabel = new JLabel(" ");
    	//mainPanel.add(emptyLabel);
     
    	JLabel spaceLab = new JLabel("   ");
    	rpmLabels.add(spaceLab);
    	mainPanel.add(spaceLab);	
     
     
     
     
    	for(int j = 0;j < 12; j ++){
    		String labelRpmVal = Integer.toString(rpmMax / 11 * j);	
    		//System.out.println(labelRpmVal);	
    		JLabel RpmLab = new JLabel(labelRpmVal);
    		rpmLabels.add(RpmLab);
    		mainPanel.add(RpmLab);	
    		}
     
     
    /*********************************************************************************************menu bar***************************/	
     
     
     
    	menuBar = new JMenuBar();
    	serialMenu = new JMenu("Serial Port");
     
    	menuBar.add(serialMenu);
    	theFrame.setJMenuBar(menuBar);
     
    	//JMenuItem comPort = new JMenu("Com Port");
    	serialMenu.addActionListener(serialMenuListener);
    	//menu.add(comPort);
     
     
    	/*JMenuItem comList = new JMenuItem("Com Port");
    	//item.addActionListener(actionListener);
    	comPort.add(comList);
    	*/
     
     
     
     
     
     
     
    	Box buttonBox = new Box(BoxLayout.Y_AXIS);
     
    	JButton fetch = new JButton ("Fetch");
    	//fetch.addActionListener(new FetchListener());
    	buttonBox.add(fetch);
     
     
     
    	JButton send = new JButton ("Send");
    	//send.addActionListener(new SendListener());
    	buttonBox.add(send);
     
    	buttonBox.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
    	background.add(BorderLayout.EAST, buttonBox);
     
     
     
     
     
     
     
    	theFrame.setBounds(300,300,300,300);
    	theFrame.pack();
    	theFrame.setVisible(true);
     
     
    }
     
     
    }


    and here the main class :


    public class mainClass {
     
     
     
    	public static void main(String[] args) throws Exception {
             SerialCommunication port = new SerialCommunication();
     
             guiPanel gui = new guiPanel();
             gui.buildGui();}
                   }



    if I add this line "System.out.println(port.getAvailablePorts()); " within the gui class, I get the error "port cannot be resolved" so I can't access the serialCommunication instance variable "port" from that class or other classes.
    Which is the correct way to do this?
    Do the classes need to be in the same package?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: interaction between serial rxtx and swing

    Where is the variable: port defined? Is it scope where you are trying to use it?

    A variable defined in a method is only available to code in that method. Define the variable at the class level. The MainClass does not do anything but hold the main() method. Don't put anything there.
    Put the definition of the variable where it can be seen by the code that needs to see it.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: interaction between serial rxtx and swing

    ok, I declared "port" in the gui class, and it works, thanks.
    Just one more question...if I have two or more classes that need to "use" the same serialcommunication class, do I need to instantiate a serialCommunication object in each class?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: interaction between serial rxtx and swing

    You probably only want to have one instance of the class for each serial port you are connecting to.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Sep 2012
    Posts
    5
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: interaction between serial rxtx and swing

    nice ques to learn from u all

Similar Threads

  1. Interaction between two label in animation
    By odiejodie in forum Java Theory & Questions
    Replies: 1
    Last Post: February 16th, 2011, 08:51 AM
  2. Interaction between components.
    By SyntheticD in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 9th, 2011, 07:32 PM
  3. Interaction with external application
    By righi in forum What's Wrong With My Code?
    Replies: 8
    Last Post: October 2nd, 2010, 08:37 AM
  4. RxTx Library issue with Lenovo R60
    By roshraj1357 in forum Java Theory & Questions
    Replies: 0
    Last Post: August 9th, 2010, 12:47 AM
  5. problem for writing to parallel port LPT1 on windows by RXTX library
    By sahar_m in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: April 20th, 2010, 04:31 AM