Java Swing学习中关于JTable遇到问题记录(二)

问题一:在JTable 中如何限制输入的最大长度?

解决方法:

1、设置给JTable的单元格添加指定控件,JTextField;

2、写一个类继承JTextField,设置JTextField编辑器与文本文档联系起来,在文本文档中可以对输入的内容过滤,通过setDocument(Document d)就可以了;

3、添加第二步中 的Document对象,在这里使用 PlainDocument的对象,重写该类的insertString方法;

在该方法中添加校验;

代码片段

table.getColumnModel().getColumn(col).setCellEditor(new DefaultCellEditor(new MyText(MAXLENGTH)));
	class MyText extends JTextField{
		
		
		
		public MyText(int maxLength) {
			superini(maxLength);
			
		}
		
		/**
		 * 设置文本框最大长度
		 * 
		 * */
		void superini(int maxLength) {
			
			
				this.setDocument(new PlainDocument() {				
				@Override
				public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
					//设置文本框中最大输入长度
					if(getLength() +str.length()>maxLength)return;
					
					if(str!= null && !str.equals("")) {						
						try {
							Integer.parseInt(str);//限制文本框中只能输入数字;
						}catch(NumberFormatException e) {				
							return;
						}
						
					}
					
					super.insertString(offs, str, a);
				}
			});
				
			
			}
			
		}
 

问题二:如何将焦点设置在指定单元格中

table.getCellEditor(row, col).getTableCellEditorComponent(table, table.getValueAt(row, col), true,row, col).requestFocus();

问题三:如何选中指定行(一行或几行);

table.setRowSelectionInterval(row1, row2);

如果row1 == row2;//选中第 row1 行;

若 row1 > row2;//则选中 区间[row2,row1];

若 row2 > row1;//则选中 区间[row1,row2];

猜你喜欢

转载自blog.csdn.net/m0_37550986/article/details/80672285