gpt4 book ai didi

java Action 监听器: retrieve TextField in a separate thread

转载 作者:行者123 更新时间:2023-11-30 06:03:34 25 4
gpt4 key购买 nike

我有一个如下所示的框架:

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);
}

}

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

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

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,如下所示:

uploadButton.addActionListener(client);

(当然下载也一样)

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

最佳答案

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

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();
}
}

关于java Action 监听器: retrieve TextField in a separate thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51810231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com