有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    您可以按如下方式操作:

    • 向用户显示JOptionPane并提示输入文本
    • 如果文本为空,即用户输入了一些字符串,则显示JFileChooser,并提示用户保存文件
    • 如果showOpenDialog的返回值为JFileChooser.APPROVE_OPTION,请使用常规I/O将文本保存到文件中

    相关文件:

    代码:

    public class Test extends JFrame implements ActionListener{
        final JFileChooser fc = new JFileChooser();
    
        public void saveTextToFile(String text) {
            
            final JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileNameExtensionFilter(".txt", "txt"));
            fileChooser.setApproveButtonText("Save");
            int actionDialog = fileChooser.showOpenDialog(this);
            if (actionDialog != JFileChooser.APPROVE_OPTION) {
                return;
            }
    
            File file = fileChooser.getSelectedFile();
            if (!file.getName().endsWith(".txt")) {
                file = new File(file.getAbsolutePath() + ".txt");
            }
    
            try {
                BufferedWriter outFile = new BufferedWriter(new FileWriter(file));
                outFile.write(text);
                outFile.flush();
                outFile.close();
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
        @Override
        public void actionPerformed(ActionEvent arg0) {
            String text = JOptionPane
                    .showInputDialog(null,
                            "Do you want to enter some random text and save it?");
            if (text != null) {
                saveTextToFile(text);
            }
        }
        private void createAndShowGui() {
            Test frame = new Test();
            JButton saveBtn = new JButton("Save Text Example");
            saveBtn.addActionListener(this);
            frame.add(saveBtn);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Test().createAndShowGui();
                }
            });
        }
    }