gpt4 book ai didi

java - 空表/树上的 SWT 自定义行高

转载 作者:行者123 更新时间:2023-11-30 09:40:20 24 4
gpt4 key购买 nike

我需要为我的表格/树行设置自定义高度。当我的表中有项目时,收听 SWT.MeasureItem 事件有效,但当我有一个空表时,它不起作用。有任何想法吗?提前致谢。

viewer.getTree().addListener(SWT.MeasureItem, new Listener() {
public void handleEvent(Event event) {
event.height = 30;
}
});

最佳答案

您是要在表格行上还是在表格本身上设置高度?

如果您尝试设置表格行的高度,SWT.MeasureItem 事件不会被触发,除非有要测量的项目 - 所以它们不会被空表格触发.请参阅(看起来有点可疑)Eclipse bug 134454 .

在内部,Table 有一个 setItemHeight(int),但您需要使用反射来访问它,因为它是受包保护的。 Reflection是一种非常有用的高级语言特性 - 特别是当您需要支持多个版本的 Java 运行时或多个版本的 SWT 时,其中添加了新方法或删除了旧方法。您可以动态查询类、方法、字段等的可用性,并仅在它们存在时调用它们。此外,您可以访问通常对调用者保护的方法和字段。我不建议经常使用 Reflection,但是当您别无选择时,最好还是使用 Reflection。

This other stackoverflow question很好地解释了如何通常调用私有(private)方法,但这里是获取 setItemHeight 方法的方法签名并调用它的具体示例:

final Table table = new Table(parent, SWT.BORDER);

/* Set up table columns, etc. */

table.pack();

try
{
/*
* Locate the method setItemHeight(int). Note that if you do not
* have access to the method, you must use getDeclaredMethod(). If
* setItemHeight(int) were public, you could simply call
* getDeclaredMethod.
*/
Method setItemHeightMethod =
table.getClass().getDeclaredMethod("setItemHeight", int.class);

/*
* Set the method as accessible. Again, this would not be necessary
* if setItemHeight(int) were public.
*/
setItemHeightMethod.setAccessible(true);

/*
* Invoke the method. Equivalent to table.setItemHeight(50).
*/
setItemHeightMethod.invoke(table, 50);
}
catch (Exception e)
{
/*
* Reflection failed, it's probably best to swallow the exception and
* degrade gracefully, as if we never called setItemHeight. Maybe
* log the error or print the exception to stderr?
*/
e.printStackTrace();
}

但是,如果您真的只是想在表格本身 上设置高度,那么使用您的布局可能会更好。例如,为 GridLayout 设置 GridData.heightHint

关于java - 空表/树上的 SWT 自定义行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9465732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com