0

我想知道如何将表格保存并加载为文本文件,这样我就不必在重新打开表格后继续将信息输入到表格中。如果可能的话,还可以导出表格和一个 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);

    }
}
4

1 回答 1

2

您可以尝试如下以txt格式保存表格的内容。.xls 如果您愿意,也可以打开格式相同的文件:

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();
}
于 2013-04-02T16:56:27.640 回答