开发者

Show "no rows found" inside a JTable row if not found entry while filtering

开发者 https://www.devze.com 2023-01-04 01:08 出处:网络
i havea JTable with row filter. once fitered if i didn\'t get any row then i ha开发者_如何学Cve to showa stringlike \"Nothing found to display \" inside table as first row.

i have a JTable with row filter.

once fitered if i didn't get any row then i ha开发者_如何学Cve to show a string like "Nothing found to display " inside table as first row.

please do needful.

Thanks , Narasimha


I needed to solve this exact problem today and wasn't able to find a good answer online. In the end I came up with my own solution, which I think may be exactly what you want. I don't know if this is too late for your project, but perhaps it can help others:

JTable.paintComponent(Graphics g) will not be called unless the table has a height that is greater than 0. This causes a problem for empty tables, so we expand the JTable height if needed so that it will always be at least the size of the JViewport that is it's parent.

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));


To show a line of text in the multicolumn table can be quite difficult, the span AFAIK is not supported. One possibility would be to hide all data columns (to show them later you have to memorize them somewhere) and show one column for the message.

An easier way would be to create a JPanel with CardLayout, add 2 cards - one containing table and one containing your empty data warning. If the filter returns empty result, show the card with empty warning, in other case - show the table.


If the filter has excluded all rows, the result returned by getViewRowCount() will be zero. You can update the GUI accordingly; setToolTipText() is handy if screen space is lacking.

Here's an example:

TableModel model = ...
JTable table = new JTable(model);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane pane = new JScrollPane(table);
JLabel label = new JLabel("");
...
String s = "Rows: " + sorter.getViewRowCount()
pane.setToolTipText(s);
label.setText(s);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号