我有一个看起来像这样的框架:
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);
(当然也可以下载)
我的难题是:如何获取文件名,即在Frame的TextField中写入的文本?我应该将此TextField作为客户端的参数吗?这会使代码看起来很奇怪,奇怪的是我不是很合逻辑,所以我希望有另一种方法。
答案 0 :(得分:1)
您可以创建两个线程,一个用于下载,一个线程用于上载
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();
}
}