没有显示将文本导入JTable

时间:2015-06-20 04:03:28

标签: java swing jtable jtextfield

我创建了一个程序,我可以在JTextField中输入数据并点击保存按钮我使用JFileChooser将数据保存在.txt文件中,其中每个JTextField都在一个新行中。我还创建了一个按钮,弹出一个JFileChooser来浏览该文件并填充其相应的单元格。

我是GUI的新手,我写的代码不起作用。我尝试了不同的变化,似乎无法得到它。有人可以指出我正确的方向。

输入

 john
Doe
st. Jude
100

这是代码

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;

//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;

public class Charity 
{
@SuppressWarnings("deprecation")
public static void main(String[] args) 
{
    JFrame frame = new JFrame("Learning Team Charity Program");
    Container cp = frame.getContentPane();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Charities
    final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
    final JComboBox selector = new JComboBox(charityArray);
    JPanel first = new JPanel();
    first.setLayout(new FlowLayout());
    first.add(selector);

    // User input JLabels and JTextFields
    JLabel nameLabel = new JLabel("First Name: ");
    final JTextField name = new JTextField();
    JLabel lastLabel = new JLabel("Last Name: ");
    final JTextField lastname = new JTextField();
    JLabel donationAmount = new JLabel("Donation Amount: ");
    final JTextField donation = new JTextField();


    JPanel second = new JPanel();
    second.setLayout(new GridLayout(4,2));
    second.add(nameLabel); second.add(name);
    second.add(lastLabel); second.add(lastname);
    second.add(donationAmount); second.add(donation);


    // Donate & Exit Buttons
    JButton donateButton = new JButton("Donate");
    JButton saveButton = new JButton("Save");
    JButton exitButton = new JButton("Exit");
    JButton openButton=  new JButton("Open File");
    JPanel third = new JPanel();
    third.setLayout(new FlowLayout());
    third.add(donateButton);
    third.add(saveButton);
    third.add(openButton);
    third.add(exitButton);

    // JTable display
    final DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("First Name");
    model.addColumn("Last Name");
    model.addColumn("Charity");
    model.addColumn("Donation");

    table.setShowHorizontalLines(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);      
    JScrollPane scrollPane = JTable.createScrollPaneForTable(table);

    JPanel fourth = new JPanel();
    fourth.setLayout(new BorderLayout());
    fourth.add(scrollPane, BorderLayout.CENTER);

    // Button Events
    exitButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            System.exit(1); 
        }
    });

    openButton.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e){
    JFileChooser openChooser = new JFileChooser();
    int openStatus = openChooser.showOpenDialog(null);
    if(openStatus == JFileChooser.APPROVE_OPTION){
        try{
            File myFile = openChooser.getSelectedFile();
            BufferedReader br = new BufferedReader(new FileReader(myFile));

            String line;        
        while((line = br.readLine())!= null){
                             model.addRow(line.split(","));           

                    }//end while
                      br.close();
                }//end try

                catch(Exception e2){
                     JOptionPane.showMessageDialog(null, "Buffer Reader Error");
                }//end catch
            }
        }


        private void setValueAt(String line, int row, int col) {
            // TODO Auto-generated method stub

        }

    });

    saveButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e){
            JFileChooser fileChooser = new JFileChooser();
            int status = fileChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION)
            {
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
                //fileChooser.setFileFilter(new FileFilter("txt"));
                PrintWriter output;
                try {
                    File file = fileChooser.getSelectedFile();
                    output = new PrintWriter(file +".txt");
                    for(int row = 0; row<table.getRowCount(); row++){
                        for(int col = 0; col<table.getColumnCount();col++){
                            output.println(table.getValueAt(row, col).toString());

                        }
                        output.println();
                    }

                    output.close();

                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }

});
    donateButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {

            DecimalFormat df = new DecimalFormat("##,###.00");
            try 
            {

                Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
                    donation.getText()};
                    model.addRow(rows);
                    name.setText("");
                    lastname.setText("");
                    donation.setText("");
            } 
            catch (Exception ex) 
            {
                JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    });

    // Frame Settings
    frame.setSize(470,300);
    //frame.setLocation(300,200);
    cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
    cp.add(first);
    cp.add(second);
    cp.add(third);
    cp.add(fourth);
    frame.setVisible(true);

    }   
}

2 个答案:

答案 0 :(得分:0)

  

我知道我必须在addRow之后在括号中传递一个值。

人们不知道这意味着什么,因为您在此处发布的代码没有addRow(...)方法。

我看到你在2小时后发布了第二个问题:https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable

将所有评论保存在一个地方,以便人们了解正在发生的事情。

另外,发布一些随机代码行对我们没有帮助,因为我们不知道代码的使用方式。例如,我不知道你是如何创建&#34;模型&#34;变量。我不知道你是否曾将模型添加到表格中。

在发布问题时发布适当的SSCCE,以便我们获得必要的信息。文件选择器与问题无关,因为我们无法访问您的真实文件。因此,您需要发布硬编码数据。一种简单的方法是使用StringReader

这是一个工作示例,演示如何将文件读取/解析/加载到JTable中:

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        try
        {
            DefaultTableModel model = new DefaultTableModel(0, 4);

            String data = "1 2 3 4\na b c d\none two three four";
            BufferedReader br = new BufferedReader( new StringReader( data ) );
            String line;

            while ((line = br.readLine()) != null)
            {
                String[] split = line.split(" ");
                model.addRow( split );
            }

            JTable table = new JTable(model);
            add( new JScrollPane(table) );
        }
        catch (IOException e) { System.out.println(e); }
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new SSCCE());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

您需要做的就是更改代码以使用FileReader而不是StringReader。

答案 1 :(得分:0)

我明白了。感谢所有那些试图提供帮助的人。

openButton.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e){
    JFileChooser openChooser = new JFileChooser();
    int openStatus = openChooser.showOpenDialog(null);
    if(openStatus == JFileChooser.APPROVE_OPTION){
        try{
            File myFile = openChooser.getSelectedFile();
            //BufferedReader br = new BufferedReader(new FileReader(myFile));
                             Scanner br = new Scanner(new FileReader(myFile));
            String line;        
        while((line = br.nextLine())!= null){
                        Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
                             model.addRow(myRow);
                            // line = br.readLine();
                                if(br.nextLine()== " "){
                                    line=br.nextLine();
                                }
                    }//end while
                      br.close();
                }//end try

                catch(Exception e2){
                     return;
                }//end catch
            }
        }

    });