如果我使用这个类:为什么我得到不可转换的类型错误?
public class BooleanTest {
public static void main(String args[]) {
final Object[] objarray = new Object[2];
try {
objarray[0] = "Hello World!";
objarray[1] = false;
} catch (NullPointerException e) {
}
boolean bool = (boolean) objarray[1];
}
}
它工作正常,我可以分配boolean
没有问题。为什么我在向用户输入密码时不能做同样的事情?
final Object result[] = new Object[2];
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,0));
JLabel label = new JLabel();
label.setHorizontalAlignment(SwingConstants.LEADING);
JTextField input = new JTextField();
input.setHorizontalAlignment(SwingConstants.CENTER);
JCheckBox checkbox = new JCheckBox("Pair with this device");
checkbox.setHorizontalAlignment(SwingConstants.LEADING);
panel.add(label);
panel.add(input);
panel.add(checkbox);
if (wrong) {
label.setText("Wrong password. Please enter the password from the other device:");
} else {
label.setText("Please enter the password from the other device:");
}
int response = JOptionPane.showConfirmDialog(SendGUI.this, panel, "Enter password", JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.OK_OPTION) {
result[0] = input.getText();
result[1] = (boolean)checkbox.isSelected();
} else {
result[0] = null;
result[1] = false;
}
}
});
} catch (InterruptedException e) {
} catch (InvocationTargetException e) {
}
boolean pair = (boolean)result[1]; //inconvertible type, expected boolean found Object
至于我可以看到我在做同样的事情在这两种情况下,但第一个例子,而第二个示例不编译罚款。
你能发布你在上一个代码中得到的错误吗? –
@MiguelPrz它是在我的代码中,'inconvertible类型,期望布尔发现对象' – Logan
@LoganDam:这是一个编译时错误?你是否在两种情况下使用相同的编译器(具有相同的选项)? –