如果在过滤时未找到条目,则在JTable行内显示"找不到行"

Nar*_*Rao 4 swing

我有一个带行滤波器的JTable.

如果我没有获得任何行,那么我必须在第一行中显示一个字符串,如"Nothing found to display".

请做到需要.

谢谢,Narasimha

小智 9

我今天需要解决这个问题,并且无法在网上找到一个好的答案.最后我提出了自己的解决方案,我认为这可能正是你想要的.我不知道这对你的项目来说是否为时已晚,但也许它可以帮助其他人:

JTable.paintComponent(Graphics g)除非表的高度大于0,否则不会被调用.这会导致空表出现问题,因此我们JTable会根据需要扩展高度,以便它始终至少JViewport是它的父级的大小.

JTable tableName =  new JTable() {
  public boolean getScrollableTracksViewportHeight() {
    if(getParent() instanceof JViewport)
      return(((JViewport)getParent()).getHeight() > getPreferredSize().height);

    return super.getScrollableTracksViewportHeight();
  }

  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if(getRowCount() == 0) {
      Graphics2D g2d = (Graphics2D) g;
      g2d.setColor(Color.BLACK);
      g2d.drawString("Nothing found to display.",10,20);
    }
  }
}

containerName.add(new JScrollPane(tableName));
Run Code Online (Sandbox Code Playgroud)