2015-05-02 2 views
0

У меня есть основной класс File и еще расширить класс File 2, как получить доступ основного класса JTextField в расширенном классе

, как я могу получить доступ к текстовому полю, объявленное в файле с AWT и свингом в расширенном класс File2?

главный класс: -

import java.util.*; 

import java.awt.Color; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.WindowAdapter; 
import java.awt.event.WindowEvent; 
import java.io.File; 
import java.sql.Statement; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class FileReceive extends FileReceiveUtil { 




    int msgIndex = 1; 
    Statement s; 
    public static File f; 
    public static String phoneNo, phoneNoLo, sk; 
    public static String str = ""; 
    public static String path = ""; 
    public String ran, ran11; 
    public String mes, sharedString; 



    FileReceive() throws Exception { 
     super("COM4"); 
    } 

    @Override 
    public void processSMS(String str) throws Exception { 
    } 

    public static void main(String[] args) throws Exception { 




     JFrame frame = new JFrame("File Receive"); 
     JPanel panel = new JPanel(); 
     panel.setLayout(new GridLayout(4, 2)); 
     frame.addWindowListener(new WindowAdapter() { 

      public void windowClosing(WindowEvent e) { 
       System.exit(0); 
      } 
     }); 

     JLabel nameId = new JLabel("Enter Destination Path"); 
     JButton browseb = new JButton("Browse"); 
     JLabel bodyTempId = new JLabel("Path : "); 
     final JTextField jtf = new JTextField(" "); 
     JButton sendB = new JButton("Receive"); 

     panel.add(nameId); 
     panel.add(browseb); 
     panel.add(bodyTempId); 
     panel.add(jtf); 
     panel.add(sendB); 
     frame.add(panel); 
     frame.setSize(300, 300); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 

     this() 


     browseb.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JFileChooser jf = new JFileChooser(); 
       String str1 = ""; 
       int m = jf.showOpenDialog(null); 
       if (m == JFileChooser.APPROVE_OPTION) { 
        f = jf.getSelectedFile(); 
        str = f.getPath(); 
        path = f.getAbsolutePath(); 
        jtf.setText(path); 
       } 
      } 
     }); 

     sendB.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 

       FileReceiveUtil util = null; 
       try { 
        util = new FileReceive(); 
       } catch (Exception ex) { 
        Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex); 
       } 
       ArrayList al = new ArrayList(); 
       try { 
        util.startReceive(al, 10); 

       } catch (Exception ex) { 
        Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex); 
       } 

      } 
     }); 

    } 

} 

Расширенный класс: -

import java.awt.event.ActionEvent; 
import java.io.*; 
import java.util.*; 
import javax.comm.*; 
import javax.swing.JTextField; 



public abstract class FileReceiveUtil implements Runnable { 

    private static int responseCode = -1; 
    private static String userCredentials = null; 
    private static String cookie = null; 
    private static String site = null; 
    private static String actionStr = null; 
    private Enumeration portList; 
    private CommPortIdentifier portId; 
    private SerialPort serialPort; 
    private OutputStream outputStream; 
    private String strPortName; 
    private InputStream inputStream; 
    private boolean boolKeepReceiving = true; 
    private Thread threadRX; 
    private ArrayList alSMSStore; 
    private int intDelay; 

    public FileReceiveUtil(String strPortName) throws Exception { 
     this.strPortName = strPortName; 
     initCommPort(); 
    } 

    private void initCommPort() throws Exception { 
     boolean boolPortOK = false; 
     portList = CommPortIdentifier.getPortIdentifiers(); 
     while (portList.hasMoreElements()) { 
      portId = (CommPortIdentifier) portList.nextElement(); 
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
       if (portId.getName().equalsIgnoreCase(strPortName)) { 
        this.serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000); 
        outputStream = serialPort.getOutputStream(); 
        inputStream = serialPort.getInputStream(); 
        serialPort.notifyOnDataAvailable(true); 
        serialPort.setSerialPortParams(230400, 
          SerialPort.DATABITS_8, 
          SerialPort.STOPBITS_1, 
          SerialPort.PARITY_NONE); 
        boolPortOK = true; 
        break; 
       } 
      } 
     } 
     if (!boolPortOK) { 
      throw new Exception("Port " + strPortName + " does not exist!"); 
     } 
    } 

    private String readSMS() throws Exception { 
     StringBuffer sb = new StringBuffer(); 
     sb.append(writeATCmd()); 
     return sb.toString(); 
    } 



    private String writeATCmd() throws Exception { 



     //Thread.sleep(2000); 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     byte[] data = new byte[1]; 
     // Thread.sleep(10); 
     int ch = inputStream.read(data); 

       //System.out.println(x); 
      bos.write(data, 0, 1); 
     byte[] bytes = bos.toByteArray();   
      File someFile = new File("D:\\yadhu.txt"); 

     FileOutputStream fos = new FileOutputStream(someFile,true); 
     fos.write(bytes); 
     fos.flush(); 
     fos.close(); 
      String str = bytes.toString(); 
     System.out.println("Data : "+ str); 
     return str; 
    } 

    private void startReceivingSMS() throws Exception { 
     final String ERROR = "ERROR"; 
     while (boolKeepReceiving) { 
      Thread.sleep(intDelay); 
      try { 
       System.out.println(" File recieved "); 







       String str = readSMS(); 

      } catch (Throwable t) { 
       System.out.println("ERROR RECEIVING MSG"); 
       t.printStackTrace(); 
      } 
     } 
    } 

    final public void startReceive(ArrayList alSMSStore, int intDelay) throws Exception { 
     this.alSMSStore = alSMSStore; 
     this.intDelay = intDelay; 
     threadRX = new Thread(this); 
     threadRX.start(); 
    } 

    final public void run() { 
     try { 
      startReceivingSMS(); 
     } catch (Throwable t) { 
      t.printStackTrace(); 
     } 
    } 

    final public void stopReceivingSMS() { 
     this.boolKeepReceiving = false; 
    } 

    public ArrayList getReceivedMessages() { 
     return this.alSMSStore; 
    } 

    private static void exit(String errorMsg) { 
     System.err.println(errorMsg); 
     System.exit(1); 
    } 

    public abstract void processSMS(String message) throws Exception; 

} 

я хочу "Файл = новый некий-файл Файл (" D: \ yadhu.txt ");", чтобы изменить это и добавьте имя файла из jtextfield на gui , пожалуйста, помогите

+0

Используйте шаблон [Observer Pattern] (http://www.oodesign.com/observer-pattern.html), чтобы 'FileReceive' мог получать обновления из' FileReceiveUtil' – MadProgrammer

+0

Если вы хотите спуститься по пути «extends» , вам нужно будет переопределить 'writeATCmd' в' FileReceive' и повторно реализовать его, чтобы использовать имя файла из 'JTextField'. Другой подход может заключаться в том, что 'FileReceiveUtil' принимает ссылку« Файл », когда его конструктор – MadProgrammer

+0

им не очень хорошо разбирается в java, поэтому можете ли вы объяснить, пожалуйста, или изменить код? пожалуйста – Sopanam

ответ

0

сделать JTextField глобальным в классе вместо локального элемента функции.

Смежные вопросы