我正在尝试将JFileChooser添加到JPanel。有时它可以正常工作,有时只显示没有JFileChooser对话框的JPanel。现在我实际上不知道该怎么做。任何人都可以帮助我吗?java GUI中的JFileChooser问题
这里是我的代码(这是一种方法):
public File chooseFileFromComputer(){
methodPanel = new JPanel();
methodPanel.setLayout(null);
methodFrame = new JFrame();
methodFrame.setTitle("File Chooser");
methodFrame.setVisible(true);
BufferedImage removeJavaImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
methodFrame.setIconImage(removeJavaImage);
methodLabel = new JLabel("Choose a file: ");
methodLabel.setBounds(10, 10, 80, 20);
methodPanel.add(methodLabel);
fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setBounds(10, 35, 550, 500);
fileChooser.setVisible(true);
add(fileChooser);
/**
* Action Events #********AE*******#
**/
fileChooser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
selectedFile = fileChooser.getSelectedFile();
methodFrame.setVisible(false);
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
methodFrame.setVisible(false);
}
}
});
//End of Action Events #________AE_______#
methodPanel.add(fileChooser);
methodFrame.setContentPane(methodPanel);
methodFrame.setResizable(false);
methodFrame.setSize(600, 600);
methodFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
return selectedFile;
}
见编辑回答。 –
请参阅第二编辑回答。我很害怕在这里挑选很多。 –