JTable选择一行,输入数字,自动向前移动一位,点击退格键,删除最后一个数字

每输入一个数字,数字向前移动一位,刚输入的数字显示在最后一个单元格,点击删除键,数字向后移动一位,删除最后一个单元格里面的数字。如下图
JTable选择一行,输入数字,自动向前移动一位,点击退格键,删除最后一个数字_第1张图片

 

 

package table; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; public class Test { JTable table = null; JineTableModel defaultModel = null; TableColumn column = null; public Test() { JFrame f = new JFrame(); String[] n = { "千", "百", "十", "元" }; defaultModel = new JineTableModel(n, 10); table = new JTable(defaultModel); table.setPreferredScrollableViewportSize(new Dimension(400, 80)); JScrollPane s = new JScrollPane(table); Container contentPane = f.getContentPane(); contentPane.add(s, BorderLayout.CENTER); table.addKeyListener(new MyListener()); f.setTitle("Test table ActionLisener"); f.setLocation(500, 300); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public class MyListener extends KeyAdapter { public void keyPressed(KeyEvent ke) { int row = table.getSelectedRow(); int cols = table.getColumnCount(); boolean accept = false; if (ke.getKeyCode() >= 48 && ke.getKeyCode() <= 57) { if (table.getValueAt(row, 0) == null) { if (ke.getKeyCode() == 48) { if (table.getValueAt(row, cols - 2) != null) { accept = true; } } else { accept = true; } } } else if (ke.getKeyCode() == 8) { if (table.getValueAt(row, cols - 1) != null) { for (int i = cols - 1; i > 0; i--) { table.setValueAt(table.getValueAt(row, i - 1), row, i); } table.setValueAt(null, row, 0); } } if (accept) { for (int i = 0; i < cols - 1; i++) { table.setValueAt(table.getValueAt(row, i + 1), row, i); } table.setValueAt(null, row, cols - 1); table.setValueAt(ke.getKeyChar(), row, cols - 1); } } } public static void main(String args[]) { new Test(); } public class JineTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; public boolean isCellEditable(int r, int c) { return false; } JineTableModel(Object[] columnNames, int rowCount) { super(columnNames, rowCount); } } }

 

运行结果

JTable选择一行,输入数字,自动向前移动一位,点击退格键,删除最后一个数字_第2张图片

你可能感兴趣的:(c,String,object,table,null,Class)