2017-03-02 92 views
0

我试图从JDateChooser获取值并将其用作文件名 我创建了一个带有路径的文件,我可以在其上写入,但唯一的问题是我可以'吨更名为变量(数据从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=] 

我该如何解决?

+0

首先,你需要从日期选择器中获取**日期**。然后你需要弄清楚如何使用与特定操作系统上的文件名兼容的字符来编写该日期(例如,'31/12/2017'将与Windows不兼容,因为'/'用于表示分离目录之间)。 –

+0

1)'btnSave.setBounds(401,215,108,30);'Java GUIs必须在不同的操作系统上工作',屏幕大小,屏幕分辨率等等,在不同的语言环境中使用不同的PLAF。因此,它们不利于像素的完美布局。请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[white space]的布局填充和边框(http://stackoverflow.com/a/17874718/ 418556)。 2)'catch(Exception k) {System.out.println(“Oops”);}'应该是catch(Exception k) {System.out.println(k.printStackTrace();}'for **有用的**信息3).. –

+0

.. 3)'新的字体(“Tahoma”,Font.PLAIN,13)'不要假定特定的字体被安装。使用通用字体(例如'Font.SERIF')或迭代字体列表并选择一个。 4)'new File(“C:\\ Users \\ student_ib \\ eclipse \\ ..'这很危险,因为目录可能不存在于用户机器上。更安全的是提供'JFileChooser'来允许用户选择一个目录,如果你喜欢,可以将该字符串设置为默认目录,如果不存在,文件选择器将忽略它,并将用户引导到其操作系统/机器上的文档目录。 –

回答

0

您必须致电day.getDate().getDay()才能获得JDateChooser的日期,而不是使用day本身。

2

你实际上是追加JDateChooser对象本身,而不是选择Date它的String表示:

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"); 
+0

getDate()方法未定义类型JDateChooser。但方法getDay()不能正常工作 –

+1

从javadoc中,有一个'getDate'方法,请检查您的JDateChooser版本:http://javadox.com/com.toedter/jcalendar/1.4/doc/api /com/toedter/calendar/JDateChooser.html – Berger

0

检查文档JDateChooser

您需要先通过.getDate().getCalendar()获取日期值,然后您应该使用类似SimpleDateFormat的格式来设置日期。

0

谢谢大家的回答。使用你的建议,我用这种方法解决了这个问题:

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