如何使Jtable单元格字符长度 [英] How to make Jtable cell character length

查看:191
本文介绍了如何使Jtable单元格字符长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的j表列限制字符,例如只允许16个字符.我尝试了各种方法,但没有用.有人可以帮助我吗?

I want to make my j table column to limit character like allowed only 16 character.I tried various methods nothing works.can anybody helps me?.

推荐答案

在此处找到答案 https://community.oracle.com/thread/1482301

自定义单元格编辑器 http://java.sun.com/docs/books /tutorial/uiswing/components/table.html#validtext 和JTextField上的自定义文档

"Custom Cell Editors http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#validtext and a custom document on a JTextField

一个价值一千个单词的示例"

One example worth thousand words"

import java.awt.*;
import javax.swing.*;
public class Test2 extends JFrame {
  public Test2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    String[] head = {"One","Two","Three"};
    String[][] data = {{"R1-C1", "12345678", "R1-C3"},
                       {"R2-C1", "R2-C2", "R2-C3"},
                       {"R3-C1", "R3-C2", "R3-C3"}};
    JTable jt = new JTable(data, head);
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    JTextField jtf = new JTextField();
    jtf.setDocument(new LimitedPlainDocument(10));
    jt.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jtf));
    setSize(300,300);
  }
  public static void main(String[] args) { new Test2().setVisible(true); }
}
class LimitedPlainDocument extends javax.swing.text.PlainDocument {
  private int maxLen = -1;
  /** Creates a new instance of LimitedPlainDocument */     
  public LimitedPlainDocument() {}
  public LimitedPlainDocument(int maxLen) { this.maxLen = maxLen; }
  public void insertString(int param, String str, 
                           javax.swing.text.AttributeSet attributeSet) 
                      throws javax.swing.text.BadLocationException {
    if (str != null && maxLen > 0 && this.getLength() + str.length() > maxLen) {
      java.awt.Toolkit.getDefaultToolkit().beep();
      return;
    }
    super.insertString(param, str, attributeSet);
  }
}

这篇关于如何使Jtable单元格字符长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆