Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Button to save data in text fields to a File

  1. #1
    Junior Member
    Join Date
    May 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Button to save data in text fields to a File

    Hello All, Good day! I'm new in Java and Hopefully you can help me with my first post

    I have a form with text fields (txt_field1, txt_field2, txt_field3) radiobutton (rad_btn1, rad_btn2) and button (btn_save, btn_cancel)

    I just want, when the user input a data in txt_field1,txt_field2,txt_field3, choose rad_btn1 and click btn_save, it will save in a file prompting "Please enter file name to save" and then it will message "File has been successfully created".

    txt_field = String
    txt_field1 = double
    txt_field2 = double

    Below is the only code that i have

     
    package finalassignment;
     
     
    public class JFrameNewAccount extends javax.swing.JFrame {
     
          public JFrameNewAccount() {
            initComponents();
        }
     
            @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            rad_savings = new javax.swing.JRadioButton();
            rad_checking = new javax.swing.JRadioButton();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            jLabel6 = new javax.swing.JLabel();
            btn_newaccountsave = new javax.swing.JButton();
            btn_newaccountcancel = new javax.swing.JButton();
            txt_accountnumber = new javax.swing.JTextField();
            txt_accountname = new javax.swing.JTextField();
            txt_initialbalance = new javax.swing.JTextField();
            txt_overdraft = new javax.swing.JTextField();
            txt_interestrate = new javax.swing.JTextField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("NEW ACCOUNT");
     
            jLabel1.setText("Account Number:");
     
            jLabel2.setText("Account Name:");
     
            jLabel3.setText("Type:");
     
            rad_savings.setText("Savings");
     
            rad_checking.setText("Checking");
     
            jLabel4.setText("Initial Balance:");
     
            jLabel5.setText("Overdraft:");
     
            jLabel6.setText("Interest Rate:");
     
            btn_newaccountsave.setText("Save");
            btn_newaccountsave.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn_newaccountsaveActionPerformed(evt);
                }
            });
     
            btn_newaccountcancel.setText("Cancel");
            btn_newaccountcancel.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn_newaccountcancelActionPerformed(evt);
                }
            });
     
            txt_accountnumber.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            txt_accountnumber.setHorizontalAlignment(javax.swing.JTextField.CENTER);
     
            txt_accountname.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            txt_accountname.setHorizontalAlignment(javax.swing.JTextField.CENTER);
     
            txt_initialbalance.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            txt_initialbalance.setHorizontalAlignment(javax.swing.JTextField.CENTER);
     
            txt_overdraft.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            txt_overdraft.setHorizontalAlignment(javax.swing.JTextField.CENTER);
     
            txt_interestrate.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            txt_interestrate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(30, 30, 30)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_accountnumber, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txt_accountname, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(rad_savings)
                                .addGap(18, 18, 18)
                                .addComponent(rad_checking))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txt_interestrate)
                                    .addComponent(txt_initialbalance)
                                    .addComponent(txt_overdraft, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(btn_newaccountsave, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(30, 30, 30)
                            .addComponent(btn_newaccountcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(10, 10, 10)))
                    .addContainerGap(43, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txt_accountnumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(txt_accountname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(rad_savings)
                        .addComponent(rad_checking))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(txt_initialbalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel5)
                        .addComponent(txt_overdraft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel6)
                        .addComponent(txt_interestrate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(27, 27, 27)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btn_newaccountsave, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btn_newaccountcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(28, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void btn_newaccountcancelActionPerformed(java.awt.event.ActionEvent evt) {                                                     
            this.setVisible(false);
        }                                                    
     
        private void btn_newaccountsaveActionPerformed(java.awt.event.ActionEvent evt) {                                                   
     
     
     
        }                                                  
     
     
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(JFrameNewAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(JFrameNewAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(JFrameNewAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(JFrameNewAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new JFrameNewAccount().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton btn_newaccountcancel;
        private javax.swing.JButton btn_newaccountsave;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JLabel jLabel6;
        private javax.swing.JRadioButton rad_checking;
        private javax.swing.JRadioButton rad_savings;
        private javax.swing.JTextField txt_accountname;
        private javax.swing.JTextField txt_accountnumber;
        private javax.swing.JTextField txt_initialbalance;
        private javax.swing.JTextField txt_interestrate;
        private javax.swing.JTextField txt_overdraft;
        // End of variables declaration                   
    }


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,541
    My Mood
    Hungover
    Thanks
    145
    Thanked 648 Times in 553 Posts

    Default Re: Button to save data in text fields to a File

    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    May 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button to save data in text fields to a File

    Hi Kevin, I just want when the user click the 'Save' button, all data in textfields will write to a file, the problem is i don't know when I'll start

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,541
    My Mood
    Hungover
    Thanks
    145
    Thanked 648 Times in 553 Posts

    Default Re: Button to save data in text fields to a File

    Quote Originally Posted by puuts View Post
    Hi Kevin, I just want when the user click the 'Save' button, all data in textfields will write to a file, the problem is i don't know when I'll start
    Did you take a look at the links I gave you? Break your problem down into much smaller pieces- can you get the text from the JTextFields? Can you print that text out to a console? Can you create a test file?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Junior Member
    Join Date
    May 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button to save data in text fields to a File

    Hi Kevin, i can write a file using console, but i don't know how to convert it to a button when clicked.

    Here's what i got.

     
    package com.ittc;
     
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
     
    public class WriteFile {
        public static void main(String args[]) throws IOException {
            System.out.println("What is the name of the file to be written to ?");
     
            String filename;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            filename = br.readLine();
            System.out.println("Enter data to write to " + filename + "...");
            System.out.println("Type q to end.");
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(filename);
            } catch (FileNotFoundException ex) {
                System.out.println("File cannot be opened for writing.");
            }
     
            try {
                boolean done = false;
                int data;
                do {
                    data = br.read();
                    if ((char) data == 'q') {
                        data = br.read();
                        if ((char) data == '$') {
                            done = true;
                        } else {
                            fos.write('q');
                            fos.write(data);
                        }
                    } else {
                        fos.write(data);
                    }
                } while (!done);
            } catch (IOException ex) {
                System.out.println("Problem in reading from the file.");
            }
        }
    }

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,541
    My Mood
    Hungover
    Thanks
    145
    Thanked 648 Times in 553 Posts

    Default Re: Button to save data in text fields to a File

    Well, can't you do something similar inside the actionPerformed() method of a JButton's ActionListener?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Junior Member
    Join Date
    May 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button to save data in text fields to a File

    Could you please cite me an example/logic on how to do it inside a button?

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,541
    My Mood
    Hungover
    Thanks
    145
    Thanked 648 Times in 553 Posts

    Default Re: Button to save data in text fields to a File

    Quote Originally Posted by puuts View Post
    Could you please cite me an example/logic on how to do it inside a button?
    There is no such notion as "inside a button". You're already using ActionListeners in your code. If you don't understand them because you used a gui builder instead of learning how to code, I suggest you start here: Trail: Creating a GUI With JFC/Swing (The Java™ Tutorials)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    Junior Member
    Join Date
    May 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button to save data in text fields to a File

    Here's what I've got.


     
     btnSaveA.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e) throws IOException{ //should it be here?
     
                    String filename;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            filename = br.readLine(); // is it correct to place it here? AFAIK all actions should place in action event. Also, it gives me error 'IOException'. I don't know where to place the 'throws IOException'
     
     
                    txt_accountname.getText();
                    txt_accountnumber.getText();
                    txt_initialbalance.getText();
                    txt_overdraft.getText();
                    if (rad_savings.isSelected()){
                        rad_savings.getText();
                    }
                    else{
                        rad_checking.getText();
                    }
                }
     
            });
            btnSaveA.addActionListener(new ActionListener(){
                private Component frame;
                public void actionPerformed(ActionEvent e){
                    System.out.println("Account has been created..");
     
                }
     
            });
         }

  10. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,541
    My Mood
    Hungover
    Thanks
    145
    Thanked 648 Times in 553 Posts

    Default Re: Button to save data in text fields to a File

    Does that code compile? Why are you calling getText() repeatedly without doing anything with the values?

    Recommended reading: Lesson: Exceptions (The Java™ Tutorials > Essential Classes)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #11
    Junior Member
    Join Date
    May 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button to save data in text fields to a File

    actually, it's not yet finish, once the textfields has been filled up and radiobutton has been picked, btnSaveA will get that texts and then write it a file. Actually, I've still in getting the text, and i having an error when coding the 'write it to a file'.

Similar Threads

  1. How to save an updated JList to a text file after the GUI closes?
    By arob317 in forum What's Wrong With My Code?
    Replies: 8
    Last Post: February 22nd, 2013, 03:56 PM
  2. Save array to text file
    By JGW in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 6th, 2013, 10:45 AM
  3. trying to save data onto a file
    By DanTheSand in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: December 13th, 2011, 09:58 AM
  4. Replies: 8
    Last Post: March 25th, 2011, 03:34 PM