JTable不会将First cell添加为空

时间:2011-12-03 07:53:55

标签: java swing jtable jframe

Jtable显示第一个单元格的空单元格是代码:

     DefaultTableModel model = new DefaultTableModel();
     table = new JTable(model){
        public boolean isCellEditable(int rowIndex, int colIndex) {
               return false; //Disallow the editing of any cell
             }};

          model.addColumn("JobID");                                              
                  model.addColumn("Job Location");
                  model.addColumn("Job Size");
                  model.addRow(new Object[]{"r5","2","3"});

输出

ID         Location     Size
(*)        2            3
对于单元格(1,1)

*为空

请帮忙。

2 个答案:

答案 0 :(得分:2)

此代码对于JTable是正确的,必须有另外一个无论生成什么......

enter image description here

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class DefTabMod extends JFrame {

    private static final long serialVersionUID = 1L;

    public DefTabMod() {

        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false; //Disallow the editing of any cell
            }
        };

        model.addColumn("JobID");
        model.addColumn("Job Location");
        model.addColumn("Job Size");
        model.addRow(new Object[]{"r5", "2", "3"});
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                DefTabMod frame = new DefTabMod();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.setLocation(150, 150);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

答案 1 :(得分:0)

这里的关键是这一行:

table.setPreferredScrollableViewportSize(table.getPreferredSize());

它解决了所有问题!