我使用windowbuilder为我的应用程序构建GUI。我为我的GUI创建了一个基于SWT的shell布局。我在GUI中有一个文本框。我想在用作GUI时从文本框中获取Integer值。我看到文本框只有选项才能获取对象或文本。有没有从文本框中获取Integer的选项?如果是这样,我该怎么做?
我从windowbuilder的源码获得的代码如下:
import org.eclipse.swt.SWT;
import otf.EnterLeaveHandler;
public class test {
protected Shell shell;
private Text text;
private final FormToolkit formToolkit = new FormToolkit(
Display.getDefault());
public static void main(String[] args) {
try {
test window = new test();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
shell = new Shell();
shell.setSize(545, 419);
shell.setText("SWT Application");
shell.setLayout(null);
Button btnNewButton = new Button(shell, SWT.NONE);
btnNewButton.setBounds(213, 243, 75, 25);
btnNewButton.setText("Ok");
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setBounds(190, 87, 137, 15);
lblNewLabel.setText("Enter function name");
text = new Text(shell, SWT.BORDER);
text.setBounds(213, 129, 76, 21);
final Label lblNewLabel_1 = formToolkit.createLabel(shell, "New Label", SWT.NONE);
lblNewLabel_1.setBounds(72, 184, 55, 15);
final EnterLeaveHandler ne = new EnterLeaveHandler();
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
Integer getvalue = Integer.parseInt(text.getText());
ne.cpuid_filter(getvalue);
}
});
}
}
答案 0 :(得分:1)
您必须从String
:
try
{
int actualValue = Integer.parseInt(text.getText());
System.out.println(actualValue);
}
catch (NumberFormatException e)
{
System.out.println("Not a number");
}
请注意,如果文本无法转换为整数,则可能会抛出NumberFormatException
。