在Java SWT中 Combo
类可以创建一个下拉框。
需要导包import org.eclipse.swt.widgets.Combo
,然后使用Combo类创建该对象。
Combo combo = new Combo(shell, SWT.NONE);
示例:
Shell shell = new Shell();
shell.setSize(583, 466);
shell.setText("SWT Application");
Combo combo = new Combo(shell, SWT.NONE); //shell是该窗口Shell对象
设置位置大小: setBounds(int x,int y , int width.int height)
; 传入参数分别为x坐标,y坐标,宽度,高度固定是28。
combo.setBounds(208, 105, 92, 28);
让下拉框显示数据用到的setText(new String[ ])
方法,传入的是一个字符串数组,每一个字符串就是每一个下拉框的选项。可以使用select(int index)
设置默认展示的一项,设置为-1为不展示数据且是默认为不展示。
要想动态展示信息,只需要在setText(new String[ ])
中传入的参数,变成数据库中读出来的即可。
代码示例:
Combo combo = new Combo(shell, SWT.NONE);
combo.setBounds(156, 78, 214,28);
String [] datas = new String[5];
datas[0] = "Java";
datas[1] = "C++";
datas[2] = "C";
datas[3] = "Python";
datas[4] = "JS";
combo.setItems( datas );
combo.select(3);
通过设置监听事件,可以获取下拉框选择的值。并且通过选择下拉框的值进行事件处理。
Combo combo = new Combo(shell, SWT.NONE);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
//处理事件
String value = combo.getText(); //获取combo下拉框选择的值
System.out.println(value);
}
});
实现如下界面,下拉框选择某项之后,下面的输入框输出选择的数。下拉框默认为第二项。
完整代码:
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class Test {
protected Shell shlTest;
private Text text;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Test window = new Test();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shlTest.open();
shlTest.layout();
while (!shlTest.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shlTest = new Shell();
shlTest.setSize(583, 466);
shlTest.setText("Test");
Label label_2 = new Label(shlTest, SWT.NONE);
label_2.setBounds(90, 159, 81, 20);
label_2.setText("你选择的是:");
Label label_1 = new Label(shlTest, SWT.NONE);
label_1.setBounds(90, 81, 76, 20);
label_1.setText("请选择:");
text = new Text(shlTest, SWT.BORDER | SWT.READ_ONLY);
text.setBounds(185, 156, 215, 26);
Combo combo = new Combo(shlTest, SWT.NONE);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String value = combo.getText();
text.setText(value);
}
});
combo.setBounds(186, 78, 214,28);
String [] datas = new String[5];
datas[0] = "Java";
datas[1] = "C++";
datas[2] = "C";
datas[3] = "Python";
datas[4] = "JS";
combo.setItems( datas );
combo.select(2);
}
}