有一種情況是我有一個ComboViewer在不同的時間會有不同的內容。因此,它有時需要重新佈局ComboViewer,以便它可以顯示完整的內容。有沒有什麼辦法可以在開始時定義ComboViewer的最大長度?如果你能給我一些想法,我將非常感激。有沒有辦法設置JFace的ComboViewer的長度?
下面的代碼是根據rudiger嘗試的演示。它在Windows 7中運行良好,而在linux 中切換到「abcedfgabcedfg」時,comboviewer的長度仍然很短。
public class ComboViewerTest {
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Comboviewer Test");
shell.setLayout(new GridLayout(1, false));
Composite composite = new Composite(shell,SWT.None);
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
composite.setLayout(new GridLayout(2, true));
final String[] txtStrings = {"a","abc"};
final String[] txtStrings2 = { "abcedfg", "abcedfgabcedfg"};
Label label = new Label(composite, SWT.NONE);
label.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1));
label.setText("comboviewer");
final ComboViewer comboViewer = new ComboViewer(composite,SWT.NONE | SWT.READ_ONLY);
Combo combo = comboViewer.getCombo();
combo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1));
comboViewer.setContentProvider(new ArrayContentProvider());
comboViewer.setInput(txtStrings);
comboViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
return super.getText(element);
}
});
Composite composite2 = new Composite(shell,SWT.None);
composite2.setLayout(new GridLayout(2, true));
Button btnNewButton = new Button(composite2, SWT.RADIO);
btnNewButton.setBounds(0, 0, 84, 29);
btnNewButton.setText("change the comboviewr");
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
comboViewer.setInput(txtStrings2);
comboViewer.getCombo().select(0);
}});
Button btnNewButton2 = new Button(composite2, SWT.RADIO);
btnNewButton2.setBounds(0, 0, 84, 29);
btnNewButton2.setText("reset");
btnNewButton2.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
comboViewer.setInput(txtStrings);
comboViewer.getCombo().select(0);
}});
comboViewer.getCombo().select(0);
setComboViewerLength(comboViewer);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private static void setComboViewerLength(ComboViewer comboViewer) {
String string = "abcedfgabcedfg";
Combo control = comboViewer.getCombo();
GC gc = new GC(control);
Point stringExtent = gc.stringExtent(string);
gc.dispose();
Rectangle bounds = control.computeTrim(0, 0, stringExtent.x, stringExtent.y);
GridData gridData = new GridData();
gridData.widthHint = bounds.width;
control.setLayoutData(gridData);
}
}
嗨Rudiger,我試着根據你的答案。我認爲這是很好的方向,而切換選區時長度仍然很短。以下是我的代碼,你可以看看我是否有錯誤。 – truejasonxiefans
由於代碼太長,所以我把它放在答案中。您可以選擇單選按鈕來更改Comboviewer的內容。雖然Combovierwer的長度在選擇「abcedfgabcedfg」時仍然很短。 – truejasonxiefans
我找不到問題。在我的Win7系統上,組合框最初的大小足以顯示最長的字符串 –