Visualizzazione dei risultati da 1 a 2 su 2

Discussione: utilizzare una classe

  1. #1

    utilizzare una classe

    dunque io ho una classe copy.java che deve sul click di un button mandarmi una stringa sulla seriale per far questo mi vorrei avvalere di una classe già trovata in rete però non capisco come utilizzarla...potreste aiutarmi


    classe copy:
    codice:
    import java.awt.*;
    import java.awt.event.*; //nuova da inserire su tutti per gestire il button
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
                    
    public class Copy extends JFrame {
     // public static void main(String[] args) {
       // new Copy(char p);
      //}
    
      private JList sampleJList;
      private JTextField valueField;
    
      private JButton button;
      
      public Copy(char p) {
        super("Copy/"+p);
        //System.out.println(p);
            
    	//JInternalFrame copy = new JInternalFrame("Copy ",true,true,true,true);
    	//copy.setSize(200,200);
    	//copy.setVisible(true);
    	
    
        WindowUtilities.setNativeLookAndFeel();
        //addInternalFrameListener(new ExitListener());
        Container content = getContentPane();
    
        // Create the JList, set the number of visible rows, add a
        // listener, and put it in a JScrollPane.
        String[] entries = { "Entry 112121212121212121212", "Entry 2", "Entry 3",
                             "Entry 4", "Entry 5", "Entry 6"};
        sampleJList = new JList(entries);
        sampleJList.setVisibleRowCount(4);
        Font displayFont = new Font("century gothic", Font.BOLD, 12);
        sampleJList.setFont(displayFont);
        sampleJList.addListSelectionListener(new ValueReporter());
        JScrollPane listPane = new JScrollPane(sampleJList);
        
        JPanel listPanel = new JPanel();
        listPanel.setBackground(Color.white);
        Border listPanelBorder =
          BorderFactory.createTitledBorder("Copy file");
        listPanel.setBorder(listPanelBorder);
        listPanel.add(listPane);
        content.add(listPanel, BorderLayout.CENTER);
    
        JLabel valueLabel = new JLabel("New name:");
        valueLabel.setFont(displayFont);
        valueField = new JTextField("None", 20);
        valueField.setFont(displayFont);
    
         
    
        button = new JButton("Copy");
        button.setActionCommand("Copy");   //nuovo
        button.addActionListener(new PushButtonActionListener());     //nuovo
    
        JPanel valuePanel = new JPanel(new GridLayout(4, 1, 2, 2));
        valuePanel.setBackground(Color.white);
        //Border valuePanelBorder =
         // BorderFactory.createTitledBorder("Edit Selection");
        //valuePanel.setBorder(valuePanelBorder);
        valuePanel.add(valueLabel);
        valuePanel.add(valueField);
        
       
    
        valuePanel.add(button);
    
        content.add(valuePanel, BorderLayout.SOUTH);
        pack();
        setVisible(true);
    
      }
    
      private class ValueReporter implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent event) {
          if (!event.getValueIsAdjusting()) 
            valueField.setText(sampleJList.getSelectedValue().toString());
        }
      }
      //actionlistener     azione di invio dei dati con il button
      private class PushButtonActionListener implements ActionListener
      {
    		public void actionPerformed(ActionEvent ae)
                    {
    			if (ae.getActionCommand().equals("Copy"))
                            {
    				//invia stringa sulla seriale
    
                                    
    			}
    		}
       }
    }
    classe che scrive sulla seriale:

    codice:
    // derived from SUN's examples in the javax.comm package
    import java.io.*;
    import java.util.*;
    //import javax.comm.*; // for SUN's serial/parallel port libraries
    import gnu.io.*; // for rxtxSerial library
    
    public class nulltest implements Runnable, SerialPortEventListener {
       static CommPortIdentifier portId;
       static CommPortIdentifier saveportId;
       static Enumeration        portList;
       InputStream           inputStream;
       SerialPort           serialPort;
       Thread           readThread;
    
       static String        messageString = "Hello, world!";
       static OutputStream      outputStream;
       static boolean        outputBufferEmptyFlag = false;
    
       public static void main(String[] args) {
          boolean           portFound = false;
          String           defaultPort;
          
          // determine the name of the serial port on several operating systems
          String osname = System.getProperty("os.name","").toLowerCase();
          if ( osname.startsWith("windows") ) {
             // windows
             defaultPort = "COM1";
          } else if (osname.startsWith("linux")) {
             // linux
            defaultPort = "/dev/ttyS0";
          } else if ( osname.startsWith("mac") ) {
             // mac
             defaultPort = "????";
          } else {
             System.out.println("Sorry, your operating system is not supported");
             return;
          }
              
          if (args.length > 0) {
             defaultPort = args[0];
          } 
    
          System.out.println("Set default port to "+defaultPort);
          
    		// parse ports and if the default port is found, initialized the reader
          portList = CommPortIdentifier.getPortIdentifiers();
          while (portList.hasMoreElements()) {
             portId = (CommPortIdentifier) portList.nextElement();
             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(defaultPort)) {
                   System.out.println("Found port: "+defaultPort);
                   portFound = true;
                   // init reader thread
                   nulltest reader = new nulltest();
                } 
             } 
             
          } 
          if (!portFound) {
             System.out.println("port " + defaultPort + " not found.");
          } 
          
       } 
    
       public void initwritetoport() {
          // initwritetoport() assumes that the port has already been opened and
          //    initialized by "public nulltest()"
    
          try {
             // get the outputstream
             outputStream = serialPort.getOutputStream();
          } catch (IOException e) {}
    
          try {
             // activate the OUTPUT_BUFFER_EMPTY notifier
             serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
             System.out.println("Error setting event notification");
             System.out.println(e.toString());
             System.exit(-1);
          }
          
       }
    
       public void writetoport() {
          System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
          try {
             // write string to serial port
             outputStream.write(messageString.getBytes());
          } catch (IOException e) {}
       }
    
       public nulltest() {
          // initalize serial port
          try {
             serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
          } catch (PortInUseException e) {}
       
          try {
             inputStream = serialPort.getInputStream();
          } catch (IOException e) {}
       
          try {
             serialPort.addEventListener(this);
          } catch (TooManyListenersException e) {}
          
          // activate the DATA_AVAILABLE notifier
          serialPort.notifyOnDataAvailable(true);
       
          try {
             // set port parameters
             serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
                         SerialPort.STOPBITS_1, 
                         SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {}
          
          // start the read thread
          readThread = new Thread(this);
          readThread.start();
          
       }
    
       public void run() {
          // first thing in the thread, we initialize the write operation
          initwritetoport();
          try {
             while (true) {
                // write string to port, the serialEvent will read it
                writetoport();
                Thread.sleep(1000);
             }
          } catch (InterruptedException e) {}
       } 
    
       public void serialEvent(SerialPortEvent event) {
          switch (event.getEventType()) {
          case SerialPortEvent.BI:
          case SerialPortEvent.OE:
          case SerialPortEvent.FE:
          case SerialPortEvent.PE:
          case SerialPortEvent.CD:
          case SerialPortEvent.CTS:
          case SerialPortEvent.DSR:
          case SerialPortEvent.RI:
          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
             break;
          case SerialPortEvent.DATA_AVAILABLE:
             // we get here if data has been received
             byte[] readBuffer = new byte[20];
             try {
                // read data
                while (inputStream.available() > 0) {
                   int numBytes = inputStream.read(readBuffer);
                } 
                // print data
                String result  = new String(readBuffer);
                System.out.println("Read: "+result);
             } catch (IOException e) {}
       
             break;
          }
       } 
    
    }

  2. #2
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,326

    Moderazione

    Quando posti del codice, specialmente se è tanto lungo come in questo caso, utilizza i tag [code] e [/code]. In questo modo il codice rimane indentato e viene formattato con un carattere che ne migliora la leggibilità.

    Ho modificato io il tuo post in questo senso.


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.