要使JTable单元格中的数据类型数字右对齐,我们需要实现一个TableModel。所述TableModel的接口getColumnClass(int index)的实现返回class的单元格值的,该信息用于通过JTable部件设置为列的默认渲染器和编辑器。
package org.nhooo.example.swing; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.awt.*; public class JTableNumberRightAlign extends JPanel { public JTableNumberRightAlign() { initializeUI(); } private void initializeUI() { setLayout(new BorderLayout()); setPreferredSize(new Dimension(450, 200)); JTable table = new JTable(new NumberTableModel()); table.setFillsViewportHeight(true); JScrollPane pane = new JScrollPane(table); add(pane, BorderLayout.CENTER); } public static void showFrame() { JPanel panel = new JTableNumberRightAlign(); panel.setOpaque(true); JFrame frame = new JFrame("JTable Number Align"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JTableNumberRightAlign.showFrame(); } }); } class NumberTableModel extends AbstractTableModel { String[] columns = {"STUDENT ID", "NAME", "YEARS", "SCORE"}; Object[][] data = { {"S001", "ALICE", 10, 8.75}, {"S002", "BOB", 10, 7.50}, {"S003", "CAROL", 10, 9.00}, {"S004", "IGNASIA", 10, 9.00}, {"S005", "MALLORY", 10, 8.50} }; public int getRowCount() { return data.length; } public int getColumnCount() { return columns.length; } @Override public String getColumnName(int column) { return columns[column]; } public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } // JTable使用此方法定义默认值 //每个单元格的渲染器或编辑器。例如,如果您有 //布尔数据,它将呈现为复选框。一种 // 数字值右对齐。 @Override public Class<?> getColumnClass(int columnIndex) { return data[0][columnIndex].getClass(); } } }
这是程序的结果: