Java 如何在EclipseSWT中基于单选按钮更改行布局结构
我想在使用SWT小部件选择单选按钮的基础上显示两个文本框。然而,当我选择另一个单选按钮时,前面的文本框应该被隐藏,并且应该显示一个下拉列表。我能够使用setVisibility(true)和false实现该功能。这里的主要问题是,当文本框不显示时(选择第二个单选按钮),文本框的空间会被占用,下拉列表会在下面显示。我不想浪费那么多空间,希望布局重叠并占用分配给它们的公共空间,因为两者不能同时使用。我有一个关于如何实现的想法,只是出于好奇而尝试了一下。因此,我只为您创建了99行代码。避免奇怪行为的基本思想是将Java 如何在EclipseSWT中基于单选按钮更改行布局结构,java,eclipse-plugin,jface,swt,Java,Eclipse Plugin,Jface,Swt,我想在使用SWT小部件选择单选按钮的基础上显示两个文本框。然而,当我选择另一个单选按钮时,前面的文本框应该被隐藏,并且应该显示一个下拉列表。我能够使用setVisibility(true)和false实现该功能。这里的主要问题是,当文本框不显示时(选择第二个单选按钮),文本框的空间会被占用,下拉列表会在下面显示。我不想浪费那么多空间,希望布局重叠并占用分配给它们的公共空间,因为两者不能同时使用。我有一个关于如何实现的想法,只是出于好奇而尝试了一下。因此,我只为您创建了99行代码。避免奇怪行为的基
Composite
子类化,并将(dis)出现的小部件放在其中。所以有三种方法是必需的:一种用于创建第一组小部件,一种用于第二组小部件,另一种用于擦除所有小部件。小部件操作后,调用布局
,以使更改生效
package test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
public class Foo {
Shell shell;
Button button1, button2;
MyComposite composite;
public Foo() {
Display display = new Display();
shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
button1 = new Button(shell, SWT.RADIO);
button1.setText("Button 1");
button1.setSelection(true);
button1.addSelectionListener(new ButtonListener());
button2 = new Button(shell, SWT.RADIO);
button2.setText("Button 2");
composite = new MyComposite();
composite.createTexts();
shell.open();
shell.pack();
while(!shell.isDisposed())
if(!display.readAndDispatch())
display.sleep();
}
/**
* A custom composite for displaying either two Combos or two Texts
*/
class MyComposite extends Composite {
/** Combos */
Combo combo1, combo2;
/** Texts */
Text text1, text2;
MyComposite() {
super(shell, SWT.NONE);
setLayout(new GridLayout(2, true));
}
/** create the combos */
void createCombos() {
combo1 = new Combo(this, SWT.DROP_DOWN);
combo1.setText("foo");
combo2 = new Combo(this, SWT.DROP_DOWN);
combo2.setText("bar");
}
/** create the texts */
void createTexts() {
text1 = new Text(this, SWT.SINGLE | SWT.BORDER);
text1.setText("foo");
text2 = new Text(this, SWT.SINGLE | SWT.BORDER);
text2.setText("bar");
}
/** dispose all children */
void disposeAll() {
for(Widget w : getChildren()) {
w.dispose();
}
}
}
class ButtonListener extends SelectionAdapter {
@Override
public void widgetSelected(SelectionEvent e) {
// erase all
composite.disposeAll();
// re-add widgets according to radio button state
if(button1.getSelection()) {
composite.createTexts();
}
else {
composite.createCombos();
}
// re-do layout and fit the shell
shell.layout();
shell.pack();
}
}
public static void main(String[] args) {
new Foo();
}
}
非常感谢菲尼亚斯。我将尝试这种方法。如有任何问题,将通知您:)