我正在使用JOptionPane.showMessageDialog(null,e,"Invalid Name",JOptionPane.ERROR_MESSAGE)方法来显示从Exception类扩展的异常.但除非我按下Alt + tab,否则Pop窗口不会显示.可能是什么原因?以下是片段.建议我一些事情.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
class NameInvalidException extends Exception {
/**
* Invalid Name
*/
String invName;
public NameInvalidException() {
super();
}
public NameInvalidException(String s) {
invName = s;
}
}
class SmallException extends Exception {
/**
* Short Name
*/
String sName;
public SmallException() {
super();
}
public SmallException(String s) {
sName = s;
}
}
public class ValidName {
public static void main(String arr[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter the name: ");
String name = br.readLine();
checkName(name);
} catch (IOException e) {
System.out.println(e);
}
}// end main
static void checkName(String name) {
try {
String sarr[] = name.split(" ");
if (sarr.length != 3)
throw new SmallException(name);
for (int j = 0; j < 3; j++) {
System.out.println("in j loop");
if (sarr[j].length() < 3) {
throw new SmallException();
}
}
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (Character.isLetter(ch) || Character.isWhitespace(ch))
System.out.println("ok " + ch);
else
throw new NameInvalidException();
}// end for
}// end try
catch (NameInvalidException e) {
JOptionPane.showMessageDialog(null, e.toString(), "Invalid Name",
JOptionPane.ERROR_MESSAGE);
System.out.println(e);
} catch (SmallException es) {
JOptionPane.showMessageDialog(null, es.toString(), "Invalid Name",
JOptionPane.ERROR_MESSAGE);
}
}// end checkName(name)
}
Run Code Online (Sandbox Code Playgroud)
我在我的机器上有相同的行为.诀窍是你必须告诉JDialog类将它自己设置在最顶层 - 这是使用方便的静态showMessageDialog方法无法实现的.所以我们必须手工创建JOptionPane和JDialog.只需向ValidName类添加另一个静态方法:
private static void showErrorPane(String message, String title) {
JOptionPane pane = new JOptionPane(message, JOptionPane.ERROR_MESSAGE);
JDialog dialog = pane.createDialog(title);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)
并调用此方法而不是JOptionPane.showMessageDialog.它适用于我的机器,错误消息出现在它应该的位置:在我的eclipse IDE之上.