Jtable标头扭曲了

时间:2013-01-27 12:49:13

标签: java swing netbeans jtable jtableheader

当我调用方法updateTable()时,表格会正确显示,但当我水平滚动表格时,某些标题会变形(错误的标题/标题会相互重叠。)。

我正在使用Netbeans我该怎么办?

public void  updateTable(String query)
{        
   try
   {     
     String sql=query;            
     PreparedStatement pst=connectionVariable.prepareStatement(sql);
     ResultSet res=pst.executeQuery();               
     myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     JScrollPane scrollpane = new JScrollPane(myTable);
     scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
     scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
     myTable.setModel(DbUtils.resultSetToTableModel(res));
     pst.close();
     res.close();
   }
   catch(Exception e) { JOptionPane.showMessageDialog(null,""+e+"","Error Updating Table",JOptionPane.ERROR_MESSAGE);  }
}

public loadTableAsPerSelection() 
{
  initComponents();
  String load_table="Select columnnames from tablenames";
  updateTable(load_table);
 }

1 个答案:

答案 0 :(得分:3)

好的,所以这里有一个40列和2000行的例子,按预期工作:

import java.awt.BorderLayout;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TestTable2 {

    protected void initUI() {
        DefaultTableModel model = new DefaultTableModel();
        for (int i = 0; i < 40; i++) {
            model.addColumn("Col-" + (i + 1));
        }
        for (int i = 0; i < 2000; i++) {
            Vector<Object> row = new Vector<Object>();
            for (int j = 0; j < 40; j++) {
                row.add("Cell " + (i + 1) + "," + (j + 1));
            }
            model.addRow(row);
        }
        JTable table = new JTable(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JFrame frame = new JFrame(TestTable2.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane scrollpane = new JScrollPane(table);
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        frame.add(scrollpane, BorderLayout.CENTER);
        frame.setSize(1000, 800);
        frame.setVisible(true);
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTable2().initUI();
            }
        });
    }

}