开发者

Java cant write in a .txt

hello i desperately need your help,well i have a jframe with a jcombobox and 3 textfields i want anything i write in the textfields and the choice i make in the combobox to be written in a .txt i tried so many things but nothing , the file is being created as Orders.txt but remains blank :S this is my code i appreciate any help Thanks :)

public class addSalesMan extends JFrame {
    private JComboBox namesJComboBox;
    private JTextField text1;//gia to poso
    private JTextField text2;//thn perigrafh
    private JTextField text3;//kai to numero ths paragelias kai ola auta tha egrafontai sto Orders.txt
    private JButton okJbutton;
    private String names[] = {"Basilis Komnhnos", "Iwanna Papadhmhtriou"};
   public String amount,name,description,number;

    public addSalesMan() {
        super("Προσθήκη παραγγελιών");
        setLayout(new FlowLayout());//dialegoume to flowlayout
//        TextFieldHandler handler = new TextFieldHandler(); writer.write(string);



            //ftiaxonoume to combobox gia tn epilogi tou onomatos
        namesJComboBox = new JComboBox(names);//orizmos JCOMBO BOX
        namesJComboBox.setMaximumRowCount(2);//na emfanizei 2 grammes
                     add(namesJComboBox);
             namesJComboBox.addItemListener(new ItemListener() {
            //xeirozome to simvan edw dhladh tn kataxwrisei ston fakelo         
           public void itemStateChanged(ItemEvent event) {
//prosdiorizoyme an eina epilegmeno to plaisio elegxou
                if (event.getStateChange() == ItemEvent.SELECTED) {                 

                            name = (names[namesJComboBox.getSelectedIndex()]);

//                            writer.newLine();             
                 setVisible(true);
            }
                 }
        });   //telos touComboBOx


        //dimioutgw pediou keimenou me 10 sthles gia thn kathe epilogh kai veveonomaste oti tha mporoume na ta epe3ergasoume kanontas ta editable

        text1 = new JTextField("Amount",10);
add(text1);
        text2 = new JTextField("Description",10);
add(text2);
        text3 = new JTextField("Order Number",10);
add(text3);

        TextFieldHandler handler = new TextFieldHandler();
        text1.addActionListener(handler);
        text2.addActionListener(handler);
        text3.addActionListener(handler);

        //private eswterikh clash gia ton xeirismo twn events twn text
//button kataxwrisis
 okJbutton=new JButton("Καταχώρηση");
 add(okJbutton);
 ButtonHandler bhandler=new ButtonHandler();
 okJbutton.addActionListener(bhandler);

    Order order=new Order(name,amount,description,number);
      Order.addOrders(name,amount,description,number);

    }
    private class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent bevent ){

             JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",bevent.getActionCommand()));


        }
    }
       private class TextFieldHandler implements ActionListener {
            //epe3ergasia twn simvantwn me kathe enter t xrhsth

            public void actionPerformed(ActionEvent evt) {
                String amount,description,number;
                amount=text1.getText();
                description=text2.getText();
                number=text3.getText();
                text1.selectAll();
                text2.selectAll();
                text3.selectAll();

              }
      if(evt.getSource()==text1 && evt.getSource()==text2 && evt.getSource()==text3){
        JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",evt.getActionCommand()));

           }
      }

//actionperformed telos
            //ean o xrhsths patisei enter sthn kathe epilogh antistixi kataxwrisi sto

            }


          public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new addSalesMan().setVisible(true);
            }
 });
      }
    }

The writers are in another class. Here is the relevant code:

public static void 开发者_Python百科addOrders(String name,String amount,String description,String o_number){
    FileOutputStream fout;
    try {
        FileWriter fstream = new FileWriter("Orders.txt");
        if(name!=null){
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(name);
            out.write(amount);
            out.write(description);
            out.write(o_number);
            out.write("\t\n");
            out.close();
        }
    } catch (IOException e) {
        System.err.println ("Unable to write to file");
        System.exit(-1);
    }
}


It looks like the main problem is that you are calling Order.addOrders() in your constructor. Instead, you should call it when a user chooses to save it's selection. I assume you would like this to happen when the user presses the button. So the code should be added in the button's ActionListener.

What you might need to try is flushing and closing the writer when a user closes your frame.

Add the following to the constructor of your frame:

addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
        writer.flush();
        writer.close();
    }
});

The above code will flush and close the writer when a user closes the frame.

Your code is unclear, so I'm not sure where the writer variable is declared, I'm just assuming it is a class level variable.

Also, you need to open your file in 'append' mode if you want to add lines to the file instead of overwriting it every time. This can be achieved through the following:

new FileWriter(yourFilePath, true); // set append to true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜