首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java actionListener:在单独的线程中检索TextField

java actionListener:在单独的线程中检索TextField
EN

Stack Overflow用户
提问于 2018-08-12 23:27:13
回答 1查看 35关注 0票数 1

我有一个框架,看起来像这样:

代码语言:javascript
复制
public class Load_Frame extends JFrame implements ActionListener{

    private JButton uploadButton, downloadButton;
    private JTextField uploadField;
    private String filename;
    private Client client;

    public Load_Frame(String username, Socket socket) {

        this.client = new Client(username, socket);

        uploadField = new JTextField ();
        uploadField.setBounds(60,100,450,30);
        uploadButton = new JButton ("Upload");
        uploadButton.setBounds(410,150,100,30);
        uploadButton.addActionListener(this);

        downloadButton = new JButton ("Download");
        downloadButton.setBounds(390,300,120,30);
        downloadButton.addActionListener(this);


        this.add(uploadField);
        this.add(uploadButton);
        this.add(downloadButton);
        this.setVisible(true);

    }

    public  void    actionPerformed(ActionEvent e)
    { 
        //Upload: 
        if  (e.getSource()== uploadButton) {
            this.filename = uploadField.getText();
            File file = new File(filename);             
            client.upload(file);
        }

        //Download
        else if (e.getSource()== downloadButton) {
            filename = (String) filesList.getSelectedItem();
            client.download(filename);
        }

}

我的问题是:我已经说过,框架和“进程”应该在不同的线程中分开,这样当进程失败时,框架就不会冻结。所以我需要我的客户成为一个新的线程。

但是,我仍然需要访问那些“上传”和“下载”按钮。我读到过我可以很容易地做到这一点:

代码语言:javascript
复制
public class Client implements Runnable, ActionListener{
    ...
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == uploadButton){
            File file  = new File(filename); //how can i retrieve the filename??
            upload(file);
    }
}

我只需要像这样在我的Frame类中添加另一个actionListener:

代码语言:javascript
复制
uploadButton.addActionListener(client);

(下载当然也一样)

我的问题是:我如何才能获得文件名,写在我的框架的TextField中的文本?我应该将此TextField作为参数提供给我的客户端吗?这会让代码看起来很奇怪,奇怪的意思是不太符合逻辑,所以我希望有另一种方法来做到这一点。

EN

回答 1

Stack Overflow用户

发布于 2018-08-13 05:07:21

您可以创建两个线程,一个用于下载,一个用于上传,如下所示

代码语言:javascript
复制
public void actionPerformed(ActionEvent e){
   if(e.getSource()==uploadButton){
      new Thread(){
         public void run(){
          this.filename = uploadField.getText();
          File file = new File(filename);
          client.upload(file);
         }
      }.start();
   }
  else if(e.getSource() == downloadButton){
    new Thread(){
      public void run(){
        this.filename = downloadField.getText();
        File file = new File(filename);
        client.download(file);
      }
    }.start();
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51810231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档