我使用上面的一些代码来创建一个“方法”来外部调用。因此,这可以允许多个弹出窗口。我的版本允许更改消息类型、标题、显示时间、屏幕位置、文本,并提供更改文本消息字体和颜色的示例。
/*
* LabelDemo.java contains a method that allow multiple popups. This version allows
* changing the message type, title, display time, screen placement, text and
* provides examples of changing the font and color of the text message.
*/
package components;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/*
* LabelDemo.java
*
*/
public class LabelDemo {
public LabelDemo() {
}
public static void main(String[] args) {
TextDisplayPopup("1st popup", "<html><font size=11 color=blue>information type",
6, 50, 105, JOptionPane.INFORMATION_MESSAGE);
TextDisplayPopup("2nd popup", "<html><font size=15 color=red>ERROR TYPE\n"
+ "<html><font size=6 color=green>2nd line with long sentence for checking"
+ " popup box dynamic sizing.",
10, 240, 240, JOptionPane.ERROR_MESSAGE);
}
public static void TextDisplayPopup(String strTitle, String strText,
int iDelayInSeconds, int iX_Location, int iY_Location, int iMessageType) {
final JOptionPane optionPane = new JOptionPane(strText,
iMessageType, JOptionPane.DEFAULT_OPTION,
null, new Object[]{}, null);
final JDialog dialog = new JDialog();
dialog.setTitle(strTitle);
dialog.setModal(false);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.pack();
dialog.setLocation(iX_Location, iY_Location);
//create timer to dispose of dialog after, iDelayInSeconds, seconds
Timer timer = new Timer(iDelayInSeconds*1000, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
dialog.dispose();
}
});
timer.setRepeats(false); // one-time use timer
// timer removes dialog after iDelayInSeconds
timer.start();
dialog.setVisible(true);
System.out.println("end of test");
}
}
输出:
1st popup
2nd popup