日期:2014-05-20  浏览次数:20649 次

请问如何自动隐藏JTABLE里面空白的行和列?
Java code

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

public class Part2 extends JFrame implements TableModelListener{
    
    private DefaultTableModel tableModel;
    private JTable tableView;
    private String[] columnNames = {"A","B","C","D","E"};
    private String[][] records;
    
    private JButton insertRow, deleteRow, save;
    private JPanel top,tablePane;
    

    public static void main(String[] args){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Part2 frame = new Part2();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public Part2() {
        records = new String[20][5];
        
        //Initialise the JButtons
        insertRow = new JButton("Insert Row");
        deleteRow = new JButton("Delete Row");
        save = new JButton("Save");
        
        //Initialise the top panel
        top = new JPanel();
        top.add(insertRow);
        top.add(deleteRow);
        top.add(save);
        add("North",top);
        
        records[0][0]="1";
        records[0][2]="2";
        /*
         * Create a JTable view and set its model. The JTable component is
         * implicitly registered as a listener of tableModel.
         */
        tableModel = new DefaultTableModel(records, columnNames);
        tableView = new JTable(tableModel);
        
        

        // Make each cell selectable.
        tableView.setRowSelectionAllowed(false);
        /*
         * Register listeners (views) with the model.
         */
        tableModel.addTableModelListener(this);        

        /* Setup the GUI. */
        setupPane(tableView);    

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 900, 300);
    }
    
    private void setupPane(JTable tableView) {
        // Create a ScrollPane to hold the JTable
        JScrollPane scrollPane = new JScrollPane(tableView);        
        scrollPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));    
        add(scrollPane); // Add the ScrollPane to JFrame
    }
    public void tableChanged(TableModelEvent e) {}
}


代码如上
代码会产生一个JTABLE,第一行会有两个格有数据,其余全部是空白的,请问该如何自动检测并隐藏那些空白的行和列但是保持tablemodel不变呢

------解决方案--------------------
Java code

int rowsNum = calLinesNum("data.txt");
        int colsNum = calTokensNum("data.txt");
        records = new String[rowsNum][colsNum];
        
        String[] columnNamesView = getColumnNamesView(columnNames,colsNum);