简体   繁体   English

从JDateChooser获取值作为文件名

[英]get value from JDateChooser as a filename

I'm trying to get value from JDateChooser and use it as a filename I've created a file with a path, I can write on it, but the only problem is I can't change its name to the variable(data from JDateChooser ) 我试图从JDateChooser获取值并将其用作文件名,我已经创建了带有路径的文件,可以在上面写,但是唯一的问题是我无法将其名称更改为变量(来自JDateChooser数据)

Here is the part of the code: 这是代码的一部分:

JButton btnSave = new JButton("Save"); 
    btnSave.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            JDateChooser day = new JDateChooser();
            try{
                    File remindFile = new File("\\path", day + ".txt");
                    remindFile.createNewFile();
                    BufferedWriter writer = new BufferedWriter(new FileWriter(remindFile));
                    writer.write(text);
                    writer.close();
                    }
                    catch(Exception k)
                    { System.out.println("Oops");}

            textField.setText(null);

        }
    });
    btnSave.setFont(new Font("Tahoma", Font.PLAIN, 13));
    btnSave.setBounds(401, 215, 108, 30);
    panel.add(btnSave);

In the result created file gets name as: 在创建的结果文件中,名称为:

com.toedter.calendar.JDateChooser
[JDateChooser,0,0,0x0,invalid,layout=java.awt.BorderLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]

How can I fix it? 我该如何解决?

You are actually appending the JDateChooser object itself, instead of a String representation of its selected Date : 实际上,您实际上是在附加JDateChooser对象本身,而不是其所选DateString表示形式:

File remindFile = new File("C:\\Users\\student_ib\\eclipse\\d", day + ".txt");

Try : 尝试:

Date chosenDate = day.getDate();
DateFormat dateFormat = new SimpleDateFormat("yyMMdd");

File remindFile = new File("C:\\Users\\student_ib\\eclipse\\d", dateFormat.parse(chosenDate) + ".txt");

您必须调用day.getDate().getDay()JDateChooser获取日期,而不要使用day本身。

Check the documentation for JDateChooser . 查看JDateChooser的文档。

You will need to first get the date value via either .getDate() or .getCalendar() , then you should use something like SimpleDateFormat to format the date. 您首先需要通过.getDate().getCalendar()获取日期值,然后应使用诸如SimpleDateFormat的格式来格式化日期。

Thank you all for your answers. 谢谢大家的答案。 Using your advices I solved it in this way: 根据您的建议,我通过以下方式解决了问题:

            int day = calendar_1.getDayChooser().getDay();
            int month = calendar_1.getMonthChooser().getMonth();
            int year = calendar_1.getYearChooser().getYear();
            String name = "" + day + month + year;
            File remindFile = new File(name + ".txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM