如何使用按钮对JTable进行排序?

huangapple go评论129阅读模式
英文:

How Can I Sort JTable With A Button?

问题

I made a table, and I want a search box for each column. I hid the column titles with this code:

我创建了一个表格,我想为每一列添加一个搜索框。我使用以下代码隐藏了列标题:

table.setTableHeader(null);

And put a textField and Button to each top of columns. Now I can search for each different column, but I can't sort the items.

然后,在每列的顶部放置了一个文本框和按钮。现在我可以为每个不同的列进行搜索,但我无法对项目进行排序。

I want to sort the column items when I click the top button. I tried some thing but it is so complex for a beginner as me.

我想在单击顶部按钮时对列项进行排序。我尝试了一些方法,但对于像我这样的初学者来说,它太复杂了。

Is there any way to do it? Or all the thing I tried useless and there is much easier way to do it? I hope explained it right.

有没有办法做到这一点?还是我尝试的一切都无效,有更简单的方法可以做到?我希望我解释清楚了。

Note:
注意:

I have found this code. I don't even know if it does what I need. I did try it but getting an error.

我找到了这段代码。我甚至不知道它是否满足我的需求。我尝试过它,但出现了错误。

/** Default sort behavior, plus every third click removes the sort. */
private final class CustomSorter extends MouseAdapter {
  @Override
  public void mouseClicked(MouseEvent aEvent) {
    int columnIdx = fTable.getColumnModel().getColumnIndexAtX(aEvent.getX());
    // build a list of sort keys for this column, and pass it to the sorter
    // you can build the list to fit your needs here
    // for example, you can sort on multiple columns, not just one
    List<RowSorter.SortKey> sortKeys = new ArrayList<>();
    // cycle through all orders; sort is removed every 3rd click
    SortOrder order = SortOrder.values()[fCountClicks % 3];
    sortKeys.add(new RowSorter.SortKey(columnIdx, order));
    fSorter.setSortKeys(sortKeys);
    ++fCountClicks;
  }
  private int fCountClicks;
}

And did try this and getting the same error.

我尝试了这个,并且得到了相同的错误。

btnNewButton.addMouseListener(new MouseAdapter() {
  @Override
  public void mouseClicked(MouseEvent e) {
    table.getRowSorter().toggleSortOrder(1);
  }
});

Error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

错误:在线程 "AWT-EventQueue-0" 中出现 java.lang.NullPointerException 错误。

This is the code: Code

这是代码:Code

This is what the program looks like: Picture

这是程序的外观:Picture

英文:

Example:

如何使用按钮对JTable进行排序?

I made a table, and I want a search box for each column. I hid the column titles with this code:

table.setTableHeader(null);

And put a textField and Button to each top of columns. Now I can search for each different column, but I can't sort the items.

I want to sort the column items when I click the top button. I tried some thing but it is so complex for a beginner as me.

Is there any way to do it? Or all the thing i tried useless and there is much easy way to do it? I hope explained it right.

Note :
I have found this code.I dont even know if it does what i need. I did try it but getting error.

/** Default sort behaviour, plus every third click removes the sort. */
  private final class CustomSorter extends MouseAdapter {
    @Override public void mouseClicked(MouseEvent aEvent) {
      int columnIdx = fTable.getColumnModel().getColumnIndexAtX(aEvent.getX());
      //build a list of sort keys for this column, and pass it to the sorter
      //you can build the list to fit your needs here 
      //for example, you can sort on multiple columns, not just one
      List&lt;RowSorter.SortKey&gt; sortKeys = new ArrayList&lt;&gt;();
      //cycle through all orders; sort is removed every 3rd click
      SortOrder order =  SortOrder.values()[fCountClicks % 3];
      sortKeys.add(new RowSorter.SortKey(columnIdx, order));
      fSorter.setSortKeys(sortKeys);
      ++fCountClicks;
    }
    private int fCountClicks;
  }
} 

And did try this and getting same error.

btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				table.getRowSorter().toggleSortOrder(1);
			}
		});

Error:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

This is the code: Code

This is the what program looks like : Picture

答案1

得分: 3

在您的JButtonActionListener中,您可以尝试使用以下代码对列进行排序:

table.getRowSorter().toggleSortOrder(columnIndex);

这将允许您点击按钮以反转排序顺序。

编辑:

正如我在评论中所说,您需要学习如何解决NullPointerException

当我运行代码时,堆栈跟踪显示:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at frame1$2.actionPerformed(frame1.java:83)

第83行是:

table.getRowSorter().toggleSortOrder(0);

因此,在该语句中有两个变量:

  1. table
  2. table.getRowSorter()

由您决定哪个变量为空

因此,您可以在该语句之前添加调试代码:

System.out.println(table);
System.out.println(table.getRowSorter());

如果您执行上述操作,您将看到table.getRowSorter()返回null。

因此,现在您可以提出一个正确的问题,比如:

“为什么table.getRowSorter()返回null?”

答案很简单,您没有设置表格的属性以进行排序。

通过添加以下代码,可以轻松地实现此目标:

table.setModel(model);
table.setAutoCreateRowSorter(true); // 添加的部分

未来在提问之前进行一些基本的调试。如果您不了解代码调试的基本知识,那么编码将会很困难。

我最初的回答是基于您已经知道如何在使用表头时对表格列进行排序,并且您只想知道如何使用单独的按钮。这就是为什么在每个问题中都应该发布一个“最小可复现示例(MRE)”,这样我们就不必猜测您的代码实际在做什么。

英文:

In the ActionListener of your JButton you can try sorting the column with code like:

table.getRowSorter().toggleSortOrder(columnIndex);

This should allow you to click the button to reverse the sort order each time it is clicked.

Edit:

As I said in my comment you need to learn how to solve a NullPointerException.

The stack trace when I run the code states:

Exception in thread &quot;AWT-EventQueue-0&quot; java.lang.NullPointerException
    at frame1$2.actionPerformed(frame1.java:83)

Line 83 is:

table.getRowSorter().toggleSortOrder(0);

So you have two variables at that statement:

  1. table
  2. table.getRowSorter()

It is up to you to determine which variable is null

So you add debug code before that statement:

System.out.println( table );
System.out.println( table.getRowSorter() );

If you do you will see that table.getRowSorter() returns null.

So now you can ask a proper question like:

"Why does table.getRowSorter() return null?"

The answer is simple you didn't set the properties of the table to do sorting.

This is easily done by adding:

table.setModel(model);
table.setAutoCreateRowSorter(true); // added

In the future do some basic debugging BEFORE asking a question. You can't code if you don't know the basics of debugging code.

My original answered assumed you new how to sort columns in a table when using the table header and you just wanted to know how to use a separate button. That is why a "MRE" should be posted with EVERY question so we don't have to guess what your code is really doing.

huangapple
  • 本文由 发表于 2020年8月12日 02:57:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63364682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定