我从 GUI 和听众开始。我想通过另一个实现 ActionListener 的类从 pc 中选择文件并将其设置到 Hlavna 类中的“File zvolenysubor”中。我可以在侦听器的 actionPerformed 方法中选择文件并将其设置为“File subor”,但我未能将其保存到我的 main 中的“File zvolenysubor”中(我的所有想法也都失败了)。请问我应该在那里更改/添加什么?
这是我的课程:
public class Hlavna {
public static void main(String[] args) {
File zvolenysubor = null;
JFrame frame = new JFrame("ABCDE");
JButton vybersuboru = new JButton("vyber");
vybersuboru.setBounds(220, 15, 200, 20);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.add(vybersuboru);
frame.setLayout(null);
VyberListener list1 = new VyberListener(zvolenysubor);
vybersuboru.addActionListener(list1);
vybersuboru.setText("vyber subor");
}
}
public class VyberListener implements ActionListener {
private File subor;
public VyberListener(File subor){
this.subor = subor;
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
System.out.println("lol");
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
chooser.showOpenDialog(null);
subor = chooser.getSelectedFile();
System.out.println(subor.getAbsolutePath());
}
}