Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将JTable保存并加载为.txt文件_Java_Arrays_Swing_Arraylist_Awt - Fatal编程技术网

Java 如何将JTable保存并加载为.txt文件

Java 如何将JTable保存并加载为.txt文件,java,arrays,swing,arraylist,awt,Java,Arrays,Swing,Arraylist,Awt,我想知道如何将我的表保存并加载为文本文件,这样我就不必在重新打开表后继续向表中输入信息。如果可能,还可以导出表格和excel文件,以便我可以在Microsoft excel中查看 import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.border.LineBorder; import java.awt.C

我想知道如何将我的表保存并加载为文本文件,这样我就不必在重新打开表后继续向表中输入信息。如果可能,还可以导出表格和excel文件,以便我可以在Microsoft excel中查看

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Window.Type;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.SystemColor;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.ArrayList;



public class Main extends JFrame  {
    private JTextField Searchtextfield;
    private JTable table;
    private JTextField Firstnametext;
    private JTextField lastnametext;
    private JTextField Phonenumbertext;
    private JTextField Emailtext;

    /**
     * Instantiates a new main.
     * 
     * This program allow you to store information in a table and export out and excel file
     * or save as a text file
     *
     * @throws Exception the exception
     */
    public Main() throws Exception  {

        getContentPane().setLayout(null);
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBackground(new Color(189, 183, 107));
        tabbedPane.setBounds(0, 32, 650, 365);
        getContentPane().add(tabbedPane);
        MaskFormatter mf2 = new MaskFormatter("(###) ###-####");

        // the main panel that hold the search bar and table
        JPanel MainPanel = new JPanel(); 
        MainPanel.setBackground(Color.LIGHT_GRAY);
        tabbedPane.addTab("Main", null, MainPanel, null);
        MainPanel.setLayout(null);

        // the search text field
        Searchtextfield = new JTextField(); 
        Searchtextfield.setBounds(485, 11, 129, 20);
        MainPanel.add(Searchtextfield);
        Searchtextfield.setColumns(10);

        // the search label on the main panel
        JLabel Searchlabel = new JLabel("Seach:"); 
        Searchlabel.setBounds(443, 14, 46, 14);
        MainPanel.add(Searchlabel);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 42, 604, 195);
        MainPanel.add(scrollPane);

        table = new JTable();
        table.setBorder(UIManager.getBorder("DesktopIcon.border"));
        scrollPane.setViewportView(table);

        // the column in the table
        table.setModel(new DefaultTableModel(

                new Object[][] {
            },
            new String[] {
                "First Name", "Last Name", "Phone Number", "Email"
            }
        ));


        // a panel that hold the first name, last name, phone number and email text field for entering 
        // information into the table on the main panel 
        JPanel AddentryPanel = new JPanel();
        AddentryPanel.setBackground(Color.LIGHT_GRAY);

        // add the entry tab for inputting information
        tabbedPane.addTab("Add Entry", null, AddentryPanel, null); 
        // set absolute layout
        AddentryPanel.setLayout(null);

        // a text field for entering you first name
        Firstnametext = new JTextField();

        Firstnametext.setBounds(175, 49, 308, 34);

        // add the first name text field to the add entry panel
        AddentryPanel.add(Firstnametext);
        Firstnametext.setColumns(10);

        JLabel lblNewLabel = new JLabel("First Name:");
        lblNewLabel.setForeground(Color.BLUE);
        lblNewLabel.setBounds(98, 59, 99, 14);
        AddentryPanel.add(lblNewLabel);

        JLabel Lastnamelabel = new JLabel("Last Name:");
        Lastnamelabel.setForeground(Color.BLUE);
        Lastnamelabel.setBounds(98, 104, 110, 14);
        AddentryPanel.add(Lastnamelabel);

        // a text field for entering you last name
        lastnametext = new JTextField();
        lastnametext.setColumns(10);
        lastnametext.setBounds(175, 94, 308, 34);

        // add the last name to the entry panel
        AddentryPanel.add(lastnametext);

        // add a formatted text field for you phone number. This field only allow number.
        Phonenumbertext = new JFormattedTextField(mf2);
        Phonenumbertext.setColumns(10);
        Phonenumbertext.setBounds(175, 145, 308, 34);

        // add the formatted text field  to entry panel
        AddentryPanel.add(Phonenumbertext);

        // a text field for entering you email 
        Emailtext = new JTextField();
        Emailtext.setColumns(10);
        Emailtext.setBounds(175, 190, 308, 34);

        // add the email text field to the add entry panel
        AddentryPanel.add(Emailtext);

        JLabel Phonenumberlabel = new JLabel("Phone Number:");
        Phonenumberlabel.setForeground(Color.BLUE);
        Phonenumberlabel.setBounds(77, 155, 93, 14);
        AddentryPanel.add(Phonenumberlabel);

        JLabel Email = new JLabel("Email:");
        Email.setForeground(Color.BLUE);
        Email.setBounds(126, 200, 54, 14);
        AddentryPanel.add(Email);

        // a button that add information into the table from the first name, last name, email
        // and you phone number field.
        JButton AddEntrybutton = new JButton("Add");

        AddEntrybutton.setForeground(Color.GREEN);

        // add a action listener for add entry button
        AddEntrybutton.addActionListener(new ActionListener() {
            /*
             * This action listener for entry button will prompt
             * you, if you want to add information into the table.
             * It also check if all the mandatory field have been filled correctly
             * so that it can proceed with the adding. If field has a error it will 
             * display a error.
             */

            public void actionPerformed(ActionEvent e) {

            // check if the option field are filled and correct before adding.
                if(Firstnametext.getText().equalsIgnoreCase("")|| Phonenumbertext.getText().equalsIgnoreCase("(   )    -    ")){
                    JOptionPane.showMessageDialog (null, "Make sure the the First Name and Phone Number field are filled"); 
                }

                // prompt if you are sure you want to add these information into the table
                else if (JOptionPane.showConfirmDialog(null, "Would you like to add these field to table?", "Request", 
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                        == JOptionPane.YES_OPTION)
                    {

                    DefaultTableModel dtm = (DefaultTableModel)table.getModel();

                    dtm.addRow(new Object[] { Firstnametext.getText(), lastnametext.getText(), Phonenumbertext.getText(), Emailtext.getText()});
                    }


            }
        });
        AddEntrybutton.setBounds(175, 253, 89, 23);

        // add the add button to the entry panel 
        AddentryPanel.add(AddEntrybutton);


        // a button the is use for clearing the field in the add entry panel
        JButton ClearButton = new JButton("Clear");
        ClearButton.setForeground(Color.RED);
        ClearButton.addActionListener(new ActionListener() {
            /*
             *  prompt you if you want to clear the first name,
             *  last name, phone number and email text field.
             *  if you select yes the field will be clear.
             *  if you select no the field will not be clear.
             */

            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(null, "Are you sure you want to clear the field?", "Request", 
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                        == JOptionPane.YES_OPTION)
                    {
                     Firstnametext.setText("");
                     lastnametext.setText("");
                     Phonenumbertext.setText("");
                     Emailtext.setText("");


                    }
                    else
                    {
                     //Go back to normal
                    }

            }
        });
        ClearButton.setBounds(394, 253, 89, 23);

        // add the clear button the entry panel
        AddentryPanel.add(ClearButton);

        // label tell that field is optional and doesn't need to be filled
        JLabel Optionallabel1 = new JLabel("Optional");

        Optionallabel1.setBounds(493, 200, 54, 14);
        AddentryPanel.add(Optionallabel1);

        // label tell that field is optional and doesn't need to be filled
        JLabel Optionallabel2 = new JLabel("Optional");

        Optionallabel2.setBounds(493, 104, 54, 14);
        AddentryPanel.add(Optionallabel2);

        // label that tell you that this field has to be filled
        JLabel Mandatorylabel1 = new JLabel("Mandatory");

        Mandatorylabel1.setForeground(Color.RED);
        Mandatorylabel1.setBounds(493, 155, 79, 14);
        AddentryPanel.add(Mandatorylabel1);

        // label that tell you that this field has to be filled
        JLabel Manatorylabel2 = new JLabel("Mandatory");

        Manatorylabel2.setForeground(Color.RED);
        Manatorylabel2.setBounds(493, 59, 64, 14);
        AddentryPanel.add(Manatorylabel2);

        // a menu bar for displaying the option to load contact, save contact, 
        // export contact as excel file and be able to close option
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(0, 0, 650, 21);
        getContentPane().add(menuBar);


        JMenu fileoption = new JMenu("File");

        menuBar.add(fileoption);


        JMenuItem loadcontact = new JMenuItem("Load Contact");

        // add load contact file to menu
        fileoption.add(loadcontact);

        JMenuItem savecontact = new JMenuItem("Save Contact");

        // add a save contact file to menu
        fileoption.add(savecontact);

        JMenuItem close = new JMenuItem("Close");
        close.addActionListener(new ActionListener() {

            /*
             * When selected the program will close.
             * 
             */
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        fileoption.add(close);
        table.getColumnModel().getColumn(2).setPreferredWidth(124);

    }


public static void main(String[] args) throws Exception {
        Main frame = new Main();
        frame.setTitle("Phone Book App");
        frame.setSize(640, 400);
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

您可以按以下方式尝试以
txt
格式保存表的内容。如果您希望:

public void saveTable()throws Exception
{
  BufferedWriter bfw = new BufferedWriter(new FileWriter("Data.txt"));
  for(int i = 0 ; i < table.getColumnCount() ; i++)
  {
    bfw.write(table.getColumnName(i));
    bfw.write("\t");
  }

  for (int i = 0 ; i < table.getRowCount(); i++)
  {
    bfw.newLine();
    for(int j = 0 ; j < table.getColumnCount();j++)
    {
      bfw.write((String)(table.getValueAt(i,j)));
      bfw.write("\t");;
    }
  }
  bfw.close();
}
public void saveTable()引发异常
{
BufferedWriter bfw=新的BufferedWriter(新的FileWriter(“Data.txt”));
对于(int i=0;i
这里是一个导出一半的Excel示例:需要扫描的代码太多了。在
StringBuilder.append()中使用字符串连接运算符(“+”)会破坏使用
StringBuilder
的全部目的。当您使用
字符串s=s1+s2时编译器将自动将其转换为
字符串s=new StringBuilder().append(s1).append(s2).toString()因此您创建了许多
StringBuilder
,尽管您已经有了一个。请用适当的
)替换这些“+”。追加(
。在重新阅读您的整个帖子之后,您已经有了一个
缓冲写入程序
,您可以直接对其进行写入,而不必使用中间
StringBuilder
,这是不必要的。@GuillaumePolet:我这样做是因为我想避免磁盘上的文件频繁I/O。。但是顺便说一下,我已经更新了它。。谢谢您的建议stion.您使用的是一个
BufferedWriter
,它将实际执行有效的IO操作,因为它将等待足够的信息准备好写入,以实际写入磁盘。如何将信息加载回表中