简体   繁体   English

使用Excel文件中的数据刷新表JTable

[英]Refresh table JTable with data from a Excel file

I have a code to populate a JTable with data from a Excel File. 我有一个代码,可以用来自Excel文件的数据填充JTable。 The problem is that after set data to the JTable, I can´t to repaint the table with the new data. 问题在于,将数据设置到JTable之后,我无法用新数据重新绘制表。 The information charging properly but no refresh the table. 信息收费正常,但没有刷新表。 I charge the data by a button "Procesar" after that select a file. 选择文件后,我通过按钮“ Procesar”对数据进行收费。 My code is: 我的代码是:

` `

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JFileChooser;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.awt.Color;
import javax.swing.JTextPane;
import java.awt.TextArea;
import javax.swing.border.MatteBorder;



public class Principal 
{
    private File file;
    Vector header = new Vector();
    Vector data = new Vector();
    DefaultTableModel model = new DefaultTableModel(data,header);

    private JFrame frame;
    private JTextField txtRuta;
    private JButton btnBuscar;
    private JButton btnProcesar;

    private MouseAdapter mouseAdapterBtnBuscar;
    private MouseAdapter mouseAdapterBtnProcesar;
    private JTextPane txtPane = new JTextPane();
    private TextArea textArea;
    private JTable table;


    /**
     * Método principal que lanza la aplicación
     */
    public static void main(String[] args) 
    {
        EventQueue.invokeLater(new Runnable() {
            public void run() 
            {
                try 
                {
                    Principal window = new Principal();
                    window.frame.setVisible(true);
                } 
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Constructor de la clase.
     */
    public Principal() {
        initialize();
    }

    /**
     * Inicializa el contenido del Frame visual.
     */
    private void initialize() 
    {
        inicializeHandlers();

        frame = new JFrame();
        frame.setBounds( 100, 100, 613, 592 );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().setLayout( null );

        btnBuscar = new JButton( "Buscar" );
        btnBuscar.addMouseListener( mouseAdapterBtnBuscar );
        btnBuscar.setBounds(498, 11, 89, 23);
        frame.getContentPane().add( btnBuscar );

        btnProcesar = new JButton( "Procesar" );
        btnProcesar.addMouseListener( mouseAdapterBtnProcesar );
        btnProcesar.setBounds( 498, 40, 89, 23 );
        frame.getContentPane().add( btnProcesar );

        txtRuta = new JTextField();
        txtRuta.setBounds( 10, 12, 478, 20 );
        frame.getContentPane().add( txtRuta );
        txtRuta.setColumns( 10 );

        textArea = new TextArea();
        textArea.setBounds(10, 88, 577, 190);
        frame.getContentPane().add(textArea);

        table = new JTable();
        table.createDefaultColumnsFromModel();

        table.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
        table.setSurrendersFocusOnKeystroke(true);
        table.setColumnSelectionAllowed(true);
        table.setCellSelectionEnabled(true);
        table.setBounds(10, 321, 577, 190);
        frame.getContentPane().add(table);
    }

    /*Método para controlar los listeners de los componentes.*/
    private void inicializeHandlers()
    {       
        mouseAdapterBtnBuscar = new MouseAdapter() 
        {
            @Override
            public void mouseClicked(MouseEvent arg0) 
            {   
                JFileChooser flsBuscador = new JFileChooser();
                int result = flsBuscador.showOpenDialog(null);

                if ( result == JFileChooser.APPROVE_OPTION )
                {
                    file = flsBuscador.getSelectedFile();
                    txtRuta.setText( file.getAbsolutePath() );
                }
            }
        };

        mouseAdapterBtnProcesar = new MouseAdapter() 
        {
            @Override
            public void mouseClicked(MouseEvent arg0)
            {   
                if ( txtRuta.getText() == null || txtRuta.getText() == "" || txtRuta.getText().endsWith(".xlsx") == false )
                {
                    JOptionPane.showMessageDialog( frame, "La ruta no es correcta o el archivo no es soportado.", "Información", JOptionPane.WARNING_MESSAGE );
                }
                else
                {
                    try
                    {
                        procesarArchivo();
                    }
                    catch( Exception ex )
                    {
                        ex.printStackTrace();
                    }
                }
            }
        };
    }

    private void procesarArchivo() throws Exception
    {
        try
        {
            if ( file != null )
            {
                String text = "Inciando lectura...\n";

                FileInputStream fis = new FileInputStream( file );

                XSSFWorkbook workbook = new XSSFWorkbook(fis);

                XSSFSheet sheet = workbook.getSheetAt(0);

                XSSFRow row;

                textArea.setText( text );

                for ( int i = 6; i < sheet.getPhysicalNumberOfRows(); i ++ )
                {
                    Vector d = new Vector();
                    row = sheet.getRow( i );

                    for ( int j = 0; j < row.getPhysicalNumberOfCells(); j++ )
                    {
                        XSSFCell cell = row.getCell( j );

                        if ( cell != null )
                        {
                            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                            {
                                if ( HSSFDateUtil.isCellDateFormatted(cell) )
                                {
                                    d.add( cell.getDateCellValue().toString().trim() );
                                    text =  text + cell.getDateCellValue().toString().trim() + "\n";
                                    textArea.setText( text );
                                }
                                else
                                {
                                    d.add( Double.toString( cell.getNumericCellValue() ).trim() );
                                    text =  text + Double.toString( cell.getNumericCellValue() ).trim() + "\n";
                                    textArea.setText( text );
                                }
                            }
                            else
                            {
                                d.add( cell.getStringCellValue().trim() );
                                text = text + cell.getStringCellValue().trim() + "\n";
                                textArea.setText( text );
                            }

                            if ( i == 6 )
                            {
                                header.add(d);
                            }
                        }
                        else
                        {
                            d.add("NULL");
                        }
                    }

                    d.add( "\n" );

                    data.add( d );

                }

                model = new DefaultTableModel(data, header);
                table.setModel(model);

                JScrollPane scroll = new JScrollPane(table);
                frame.getContentPane().add( scroll );

            }
        }
        catch( Exception ex )
        {
            ex.printStackTrace();
        }
    }
}

` `

Thanks for your help; 谢谢你的帮助;

In your procesarArchivo() method... How many times do you want to add a table to frame's content pane? 在您的procesarArchivo()方法中...您想要将表添加到框架的内容窗格中多少次?

JScrollPane scroll = new JScrollPane(table);
frame.getContentPane().add( scroll );

In your current code every time btnProcesar is pressed a new JTable is added to frame's content pane. 在您当前的代码中,每次按下btnProcesar都会将新的JTable添加到框架的内容窗格中。 You just can't see it because you don't call revalidate() method: 您只是看不到它,因为您没有调用revalidate()方法:

frame.getContentPane().revalidate();

Form Container.add() javadoc: 形成Container.add() javadoc:

This method changes layout-related information, and therefore, invalidates the component hierarchy. 此方法更改与布局有关的信息,因此使组件层次结构无效。 If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component. 如果已经显示了容器,则此后必须验证层次结构才能显示添加的组件。

If you do call revalidate() method you'll see 2 tables, then 3 and so on and that's not what you want. 如果您调用revalidate()方法,则会看到2个表,然后是3个表,依此类推,这不是您想要的。 Don't add a new JTable . 不要添加新的JTable Add just one JTable and refresh its TableModel instead. 仅添加一个JTable并刷新其TableModel

Some other tips: 其他一些技巧:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM