我有一个框架,看起来像这样:
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中的文本?我应该将此TextField作为参数提供给我的客户端吗?这会让代码看起来很奇怪,奇怪的意思是不太符合逻辑,所以我希望有另一种方法来做到这一点。
发布于 2018-08-13 05:07:21
您可以创建两个线程,一个用于下载,一个用于上传,如下所示
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();
}
}
https://stackoverflow.com/questions/51810231
复制相似问题