簡體   English   中英

從JDateChooser獲取值作為文件名

[英]get value from JDateChooser as a filename

我試圖從JDateChooser獲取值並將其用作文件名,我已經創建了帶有路徑的文件,可以在上面寫,但是唯一的問題是我無法將其名稱更改為變量(來自JDateChooser數據)

這是代碼的一部分:

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);

在創建的結果文件中,名稱為:

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=]

我該如何解決?

實際上,您實際上是在附加JDateChooser對象本身,而不是其所選DateString表示形式:

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

嘗試:

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本身。

查看JDateChooser的文檔。

您首先需要通過.getDate().getCalendar()獲取日期值,然后應使用諸如SimpleDateFormat的格式來格式化日期。

謝謝大家的答案。 根據您的建議,我通過以下方式解決了問題:

            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