【发布时间】:2018-08-12 15:27:12
【问题描述】:
我有一个看起来像这样的框架:
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 作为我的客户的参数吗?这会使代码看起来很奇怪,而且我所说的奇怪是指不太合乎逻辑,所以我希望有另一种方法。
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
1) 我确实试图让它简短,但是,它是一个框架,里面有很多内容......另外,上次我削减我的代码只让有问题的部分,人们赞扬“缺失的部分”。 2)当然。然而,这只是一个有时间限制的“学生作品”,UI 根本不重要(我的老师就像“哦,你做了一个 UI?”)。另外,这是我第一次使用 Java,我已经必须使用多线程,所以我暂时不会尝试使用布局管理器。
-
1) 您过于关注“short”/“minimal”,而对其他短语的关注不够。 MCVE / SSCCE 应该是这样的,我们可以复制/粘贴、编译/运行并查看问题而无需更改。 2) 如果讲师没有指定,不要浪费时间制作 GUI。正如你所提到的,这并不令人印象深刻。更好地关注问题的核心。
标签: java multithreading swing jtextfield