2

我有一个代码可以用 Excel 文件中的数据填充 JTable。问题是在将数据设置到 JTable 之后,我不能用新数据重新绘制表格。信息正常收费但没有刷新表格。选择文件后,我通过“Procesar”按钮对数据进行收费。我的代码是:

`

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();
        }
    }
}

`

谢谢你的帮助;

4

1 回答 1

1

在您的procesarArchivo()方法中...您想将表格添加到框架的内容窗格多少次?

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

在您当前的代码中,每次btnProcesar按下一个新JTable的都会添加到框架的内容窗格中。您只是看不到它,因为您没有调用revalidate()方法:

frame.getContentPane().revalidate();

表格Container.add() javadoc:

此方法更改与布局相关的信息,因此使组件层次结构无效。如果容器已显示,则必须随后验证层次结构以显示添加的组件。

如果您确实调用revalidate()方法,您将看到 2 个表,然后是 3 个,依此类推,这不是您想要的。不要添加新的JTable. 只添加一个JTable并刷新它TableModel

其他一些提示:

于 2013-10-24T23:52:28.380 回答