廊坊专业网站建设,给我免费播放片国语电影,软件app定制开发,成都网站建设中心问题
在数据回显时#xff0c;明明在代码中通过comboViewer.setSelection设置了默认值#xff0c;但没有生效#xff08;回显#xff09;#xff0c;是怎么回事呢 #xff1f;
分析
如果comboViewer.setSelection(new StructuredSelection(items[1]))不起作用#xf…问题
在数据回显时明明在代码中通过comboViewer.setSelection设置了默认值但没有生效回显是怎么回事呢
分析
如果comboViewer.setSelection(new StructuredSelection(items[1]))不起作用可能是由于以下原因之一 内容提供者(Content Provider)设置了不同的元素类型在使用StructuredSelection设置选中项时它需要与ComboViewer内容提供者返回的元素类型匹配。如果它们不匹配StructuredSelection将无法识别要选中的元素。例如如果ComboViewer的内容提供者返回的是Person对象那么在使用StructuredSelection设置选中项时需要使用new StructuredSelection(selectedPerson)。 选中项不存在于ComboViewer的内容中当使用StructuredSelection设置选中项时确保它存在于ComboViewer的内容中。否则ComboViewer将不会选择任何项。 选中项在内容提供者中具有不同的对象实例当使用StructuredSelection设置选中项时它需要与ComboViewer内容提供者返回的元素对象实例匹配。如果它们不匹配StructuredSelection将无法识别要选中的元素。在这种情况下可以尝试在内容提供者中为每个元素返回一个唯一的标识符并使用StructuredSelection设置选中项时将标识符作为参数传递。
如果您仍然无法解决问题请检查控件的其他设置和属性以确保它们没有干扰选中项的设置。例如将ComboViewer的样式设置为SWT.READ_ONLY以确保用户无法手动更改选中项。
解决方案
1、首先要根据检查代码根据以上分析代码片段的顺序应该如下
ComboViewer comboViewer new ComboViewer(parent, SWT.READ_ONLY);
comboViewer.setContentProvider(ArrayContentProvider.getInstance());
comboViewer.setInput(new String[] {Item 1, Item 2, Item 3});
comboViewer.setSelection(new StructuredSelection(Item 1));注意setInput 一定能要在 setSelection 之前
2、按照1处理了依然不能回显应使用如下代码片段处理 这种情况在对元素是对象时常出现 示例如下
// 定义 Book 类
class Book {private int id;private String name;private double price;private String publish;public Book(int id, String name, double price, String publish) {this.id id;this.name name;this.price price;this.publish publish;}public int getId() {return id;}public String getName() {return name;}public double getPrice() {return price;}public String getPublish() {return publish;}Overridepublic String toString() {return name ( price );}
}// 创建 Book 列表
ListBook books new ArrayList();
books.add(new Book(1, Book 1, 10.0, Publisher 1));
books.add(new Book(2, Book 2, 20.0, Publisher 2));
books.add(new Book(3, Book 3, 30.0, Publisher 3));// 创建 ComboViewer 控件并设置内容提供者和标签提供者
ComboViewer comboViewer new ComboViewer(parent, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.BORDER);
comboViewer.setContentProvider(new ArrayContentProvider());
comboViewer.setLabelProvider(new LabelProvider() {Overridepublic String getText(Object element) {if (element instanceof Book) {Book book (Book) element;return String.format( %s (%d),book.getName(),book.getPrice());}return super.getText(element);}
});// 将 Book 列表设置为 ComboViewer 的输入
comboViewer.setInput(books);// 设置默认选中项为第一个元素
Book bookformDB bookformDB();// 从数据库查找到的用于回显
comboViewer.setSelection(new StructuredSelection(bookformDB));3、如果还不能显示在设置时做如下处理
在 2 中的代码上做修改
// 设置默认选中项为第一个元素
Book bookformDB bookformDB();// 从数据库查找到的用于回显
// 应查找books中的bk查找出来将其设置为默认值亲测有效
for(Book bk : books){if(bk.getId() bookformDB.getId()){comboViewer.setSelection(new StructuredSelection(bk));}
}