java - 为什么 sun.swing.FilePane 可以强制转换为 javax.swing.table?
问题描述
所以,我正在寻找一种按日期对 jFileChooser 进行排序的方法,我发现了这个讨论:Start a JFileChooser with files ordered by date
该解决方案有效。虽然,这段代码让我感到困惑:
JTable table = SwingUtils.getDescendantsOfType(JTable.class, fileChooser).get(0);
我决定使用 println() 检查表实例的类型,结果如下:sun.swing.FilePane$6...
这个 FilePane 引起了我的兴趣。所以,我决定寻找 FilePane 的源代码,我发现了这个: http: //www.docjar.com/html/api/sun/swing/FilePane.java.html
在源代码中,FilePane 没有扩展 JTable。不过,FilePane 将 JTable 作为组件。FilePane 怎么可能被转换成 JTable?
我查看了 SwingUtils 源代码,发现了一些 getDescendantsOfType() 方法的实现。
public static <T extends JComponent> List<T> getDescendantsOfType(
Class<T> clazz, Container container) {
return getDescendantsOfType(clazz, container, true);
}
public static <T extends JComponent> List<T> getDescendantsOfType(
Class<T> clazz, Container container, boolean nested) {
List<T> tList = new ArrayList<T>();
for (Component component : container.getComponents()) {
if (clazz.isAssignableFrom(component.getClass())) {
tList.add(clazz.cast(component));
}
if (nested || !clazz.isAssignableFrom(component.getClass())) {
tList.addAll(SwingUtils.<T>getDescendantsOfType(clazz,
(Container) component, nested));
}
}
return tList;
}
我尝试使用 cast 运算符将 FilePane 转换为 JTable,但没有成功。我对Class<T>类知之甚少,所以我对这个类的方法不是很熟悉。
解决方案
In the source code, FilePane doesn't extend JTable.
Correct.
How is it possible for FilePane to be casted to JTable?
It can't.
sun.swing.FilePane$6...
The $6 implies that it is an inner class defined in the FilePane class.
Inner class names start at $1 and increase for each inner class.
From the class you can see:
final JTable detailsTable = new JTable(getDetailsTableModel()) {
// Handle Escape key events here
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE && getCellEditor() == null) {
// We are not editing, forward to filechooser.
chooser.dispatchEvent(e);
return true;
}
return super.processKeyBinding(ks, e, condition, pressed);
}
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
// update header with possibly changed column set
updateDetailsColumnModel(this);
}
}
};
You can see the JTable inner class overrides the:
- processKeyBinding(), and
- tableChanged()
methods.
You should be able to see inner class files when you compile your source code and use inner classes.
推荐阅读
- has-many - 关系计数的环回过滤器
- ios - 如何在 iOS 中触发 textField(_:shouldChangeCharactersIn:replacementString:) 方法
- amazon-web-services - 为什么我的 MERN 堆栈 Web 应用在部署后不加载其主页?
- latex - Latex 将文本文件中的数字转换为饼图的变量
- svg - 如何将 SVG 文件转换为 JPEG?
- ios - 是否可以在 iOS 应用程序中运行 UITest?
- reactjs - 使用 apache 在 EC2 服务器上创建和部署 React 应用程序
- python - django:被引用表“tcReports_global_users”中没有与外键“fk”中的引用列列表匹配的主键或候选键
- swift - 如何从 `Button` 的动作或 `Binding` 引用 `actor` 的属性?
- java - 如何在 Java SE 11 中使用自定义注解?