`
touchinsert
  • 浏览: 1289455 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Java实现MessageBox类

阅读更多

MessageBox类弹出Java应用程序的警告,错误。

package com.nova.colimas.install;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;
import java.awt.*;

public class MessageBox implements Runnable, ActionListener, WindowListener,
KeyListener {

// ---------- Private Fields ------------------------------
private ActionListener listener;

private JDialog dialog;

private String closeWindowCommand = "CloseRequested";

private String title;

private JFrame frame;

private boolean frameNotProvided;

private JPanel buttonPanel = new JPanel();


// ---------- Initialization ------------------------------
/**
* This convenience constructor is used to delare the listener that will be
* notified when a button is clicked. The listener must implement
* ActionListener.
*/
public MessageBox(ActionListener listener) {
this();
this.listener = listener;
}

/**
* This constructor is used for no listener, such as for a simple okay
* dialog.
*/
public MessageBox() {
}

// Unit test. Shows only simple features.
public static void main(String args[]) {
MessageBox box = new MessageBox();
box.setTitle("Test MessageBox");
box.askYesNo("Tell me now.\nDo you like Java?");
}

// ---------- Runnable Implementation ---------------------
/**
* This prevents the caller from blocking on ask(), which if this class is
* used on an awt event thread would cause a deadlock.
*/
public void run() {
dialog.setVisible(true);
}

// ---------- ActionListener Implementation ---------------
public void actionPerformed(ActionEvent evt) {
dialog.setVisible(false);
dialog.dispose();
if (frameNotProvided)
frame.dispose();
if (listener != null) {
listener.actionPerformed(evt);
}
}

// ---------- WindowListener Implementatons ---------------
public void windowClosing(WindowEvent evt) {
// User clicked on X or chose Close selection
fireCloseRequested();
}

public void windowClosed(WindowEvent evt) {
}

public void windowDeiconified(WindowEvent evt) {
}

public void windowIconified(WindowEvent evt) {
}

public void windowOpened(WindowEvent evt) {
}

public void windowActivated(WindowEvent evt) {
}

public void windowDeactivated(WindowEvent evt) {
}

// ---------- KeyListener Implementation ------------------
public void keyTyped(KeyEvent evt) {
}

public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
fireCloseRequested();
}
}

public void keyReleased(KeyEvent evt) {
}

private void fireCloseRequested() {
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
closeWindowCommand);
actionPerformed(event);
}

// ---------- Public Methods ------------------------------
/**
* This set the listener to be notified of button clicks and WindowClosing
* events.
*/
public void setActionListener(ActionListener listener) {
this.listener = listener;
}

public void setTitle(String title) {
this.title = title;
}

/**
* If a Frame is provided then it is used to instantiate the modal Dialog.
* Otherwise a temporary Frame is used. Providing a Frame will have the
* effect of putting the focus back on that Frame when the MessageBox is
* closed or a button is clicked.
*/
public void setFrame(JFrame frame) { // Optional
this.frame = frame;
}

/**
* Sets the ActionCommand used in the ActionEvent when the user attempts to
* close the window. The window may be closed by clicking on "X", choosing
* Close from the window menu, or pressing the Escape key. The default
* command is "CloseRequested", which is just what a Close choice button
* would probably have as a command.
*/
public void setCloseWindowCommand(String command) {
closeWindowCommand = command;
}

/**
* The
*
* @param label
* will be used for the button and the
* @param command
* will be returned to the listener.
*/
public void addChoice(String label, String command) {
JButton button = new JButton(label);
button.setActionCommand(command);
button.addActionListener(this);
button.addKeyListener(this);

buttonPanel.add(button);
}

/**
* A convenience method that assumes the command is the same as the label.
*/
public void addChoice(String label) {
addChoice(label, label);
}

/**
* One of the "ask" methods must be the last call when using a MessageBox.
* This is the simplest "ask" method. It presents the provided
*
* @param message.
*/
public void ask(String message) {
if (frame == null) {
frame = new JFrame();
frameNotProvided = true;
} else {
frameNotProvided = false;
}
dialog = new JDialog(frame, true); // Modal
dialog.addWindowListener(this);
dialog.addKeyListener(this);
dialog.setTitle(title);
dialog.setLayout(new BorderLayout(5, 5));

JPanel messagePanel = createMultiLinePanel(message);
JPanel centerPanel = new JPanel();
centerPanel.add(messagePanel);
dialog.add("Center", centerPanel);
dialog.add("South", buttonPanel);
dialog.pack();
enforceMinimumSize(dialog, 200, 100);
centerWindow(dialog);
Toolkit.getDefaultToolkit().beep();

// Start a new thread to show the dialog
Thread thread = new Thread(this);
thread.start();
}

/**
* Same as ask(String message) except adds an "Okay" button.
*/
public void askOkay(String message) {
addChoice("Okay");
ask(message);
}

/**
* Same as ask(String message) except adds "Yes" and "No" buttons.
*/
public void askYesNo(String message) {
addChoice("Yes");
addChoice("No");
ask(message);
}

// ---------- Private Methods -----------------------------
private JPanel createMultiLinePanel(String message) {
JPanel mainPanel = new JPanel();
GridBagLayout gbLayout = new GridBagLayout();
mainPanel.setLayout(gbLayout);
addMultilineString(message, mainPanel);
return mainPanel;
}

// There are a variaty of ways to do this....
private void addMultilineString(String message, Container container) {

GridBagConstraints constraints = getDefaultConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
// Insets() args are top, left, bottom, right
constraints.insets = new Insets(0, 0, 0, 0);
GridBagLayout gbLayout = (GridBagLayout) container.getLayout();

while (message.length() > 0) {
int newLineIndex = message.indexOf('\n');
String line;
if (newLineIndex >= 0) {
line = message.substring(0, newLineIndex);
message = message.substring(newLineIndex + 1);
} else {
line = message;
message = "";
}
JLabel label = new JLabel(line);
gbLayout.setConstraints(label, constraints);
container.add(label);
}
}

private GridBagConstraints getDefaultConstraints() {
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.gridheight = 1; // One row high
// Insets() args are top, left, bottom, right
constraints.insets = new Insets(4, 4, 4, 4);
// fill of NONE means do not change size
constraints.fill = GridBagConstraints.NONE;
// WEST means align left
constraints.anchor = GridBagConstraints.WEST;

return constraints;
}

private void centerWindow(JDialog win) {
Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
// If larger than screen, reduce window width or height
if (screenDim.width < win.getSize().width) {
win.setSize(screenDim.width, win.getSize().height);
}
if (screenDim.height < win.getSize().height) {
win.setSize(win.getSize().width, screenDim.height);
}
// Center Frame, Dialogue or Window on screen
int x = (screenDim.width - win.getSize().width) / 2;
int y = (screenDim.height - win.getSize().height) / 2;
win.setLocation(x, y);
}

private void enforceMinimumSize(JDialog comp, int minWidth, int minHeight) {
if (comp.getSize().width < minWidth) {
comp.setSize(minWidth, comp.getSize().height);
}
if (comp.getSize().height < minHeight) {
comp.setSize(comp.getSize().width, minHeight);
}
}

} // End class

在调用它的WindowsMain类里添加一个Close按钮,点击Close按钮时调用MessageBox选择yes或no。

jCloseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
//System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
MessageBox box = new MessageBox();
box.setTitle("Warning");
box.askYesNo("Do you really want to exit?");

//添加MessageBox的按钮事件Listener。
box.setActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e){
JButton button=(JButton)e.getSource();
if(button.getText()=="Yes")
System.exit(0);
}
}
);
}
});

分享到:
评论

相关推荐

    航空订票系统java源码-Decibel-Airlines-Reservation-System:一个用Java开发的飞机预订系统

    TextBox、Label、Buttons、Table、MessageBox 等)在 Java GUI 应用程序中开发用户界面。 使用面向对象的编程知识在多个表单应用程序之间解析数据。 为程序实现了座位预订功能: CancelSeat 、 ConfirmSeat 、 ...

    招生管理数据库系统(sql)

    系统组件图:系统包括4个类包:UI包、商业对象包、效用包和数据库包,以及一个启动程序组件StartClass.java。招生管理系统的组件图如图3-7所示。 图3-7 系统的组件图 四、系统部署 招生管理系统的配置图,如...

    [原创]用SWT/JFace实现的深路径自动生成软件(附源码)

    不过由于是SWT+JFace实现的桌面程序,想研究Java桌面程序应用的朋友也可以下载看看,其一些特性及设计思路还是比较有用的。 &lt;br&gt;详细资料及截图请参考压缩包中doc/how to run.doc文档 &lt;br&gt;新特性: 支持拽...

    在javascript中使用com组件的简单实现方法

    // TODO: 在此添加实现代码  MessageBox(NULL,L"test",L"test",MB_OK);  return S_OK;  }  STDMETHODIMP Ctest::test1(BSTR a1) //有一个字符串输入参数  {  // TODO: 在此添加实现代码  MessageBox...

    实验三Socket通信实验报告.doc

    //以指定的编码,从缓冲区中解析出内容 MessageBox.Show ( sMessage ) ; //显示传送来的数据 } 1.2利用NetworkStream来传送信息 TcpClient tcpc = new TcpClient ( "10.138.198.213" , 8888 ) ; //对IP地址为"10....

    Eclipse_Swt_Jface_核心应用_部分19

    8.2.3 实现接口的类 131 8.2.4 继承的类的方法 132 8.3 键盘事件 132 8.3.1 键盘事件程序示例 132 8.3.2 键盘事件的各种属性 134 8.4 鼠标事件 136 8.4.1 鼠标事件程序示例 136 8.4.2 鼠标事件的各种...

    精通JS脚本之ExtJS框架.part2.rar

    1.1.3 JavaScript与Java 1.2 第一个JavaScript程序 1.2.1 嵌入JavaScript 1.2.2 链接外部JavaScript文件 1.2.3 注意事项 1.3 基础语法 1.3.1 数据类型 1.3.2 变量与常量 1.3.3 运算符 1.4 流程控制语句 ...

    精通JS脚本之ExtJS框架.part1.rar

    1.1.3 JavaScript与Java 1.2 第一个JavaScript程序 1.2.1 嵌入JavaScript 1.2.2 链接外部JavaScript文件 1.2.3 注意事项 1.3 基础语法 1.3.1 数据类型 1.3.2 变量与常量 1.3.3 运算符 1.4 流程控制语句 ...

    asp.net知识库

    运算表达式类的原理及其实现 #实现的18位身份证格式验证算法 身份证15To18 的算法(C#) 一组 正则表达式 静态构造函数 忽略大小写Replace效率瓶颈IndexOf 随机排列算法 理解C#中的委托[翻译] 利用委托机制处理.NET中...

    Ext Js权威指南(.zip.001

    1.2.6 在java中使用json / 12 1.2.7 更多有关json的信息 / 15 1.3 ext js 4概述 / 15 1.4 ext js的开发工具的获取、安装与配置介绍 / 18 1.4.1 ext designer / 18 1.4.2 在visual studio中实现智能提示 / 23 ...

    飞鸽传书(IPMessenger) 源码

    可运行于多种操作平台(Win/Mac/UNIX/Java),并实现跨平台信息交流。不需要服务器支持, 支持文件/文件夹的传送 (2.00版以上),通讯数据采用 RSA/Blofish 加密 (2.00版以上),十分小巧,简单易用,而且你可以完全免费...

    javascript验证身份证完全方法具体实现

    代码如下:var certCardValid = function(id){ var arrVerifyCode = [1,0,”x”,9,8,7,6,5,4,3,2]; var wi = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]; var Checker = [1,9,8,7,6,5,4,3,2...= 18) { Ext.MessageBox.alert

    一验证码识别的小程序源码

    印象中有个java版本的订票程序里面有个验证码识别功能,用tesseract-ocr来识别验证码的,如果验证码不是很复杂识别效果还可以。 开发环境 vs2008 开发语言C# 使用方法很简单 1.下载tesseract 的.net 类库tessnet...

    KISDJ语音聊天

    本程序,实现一个简单的语音聊天功能,将麦克风采集到的音频数据经G711压缩后,通过UDP协议传输。在本文中 不讨论如何通过麦克风采集音频数据,也不讨论G711压缩的细节,相关内容可以查看文章后参考文献的内容。 ...

    SqliteDev 384

     MessageBox Show sb ToString ;"&gt;SQLite 是一款轻型的数据库 是遵守ACID的关联式数据库管理系统 它的设计目标是嵌入式的 而且目前已经在很多嵌入式产品中使用了它 它占用资源非常的低 在嵌入式设备中 可能只需要几...

    SQLite(SqliteDev)

    SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能... MessageBox.Show(sb.ToString());

    Visual C++ 编程资源大全(英文源码 其它)

    38.zip Messagebox with printf capability 有printf能力的Messagebox(4KB)&lt;END&gt;&lt;br&gt;39,39.zip Multiple Level Undo/Redo 多级Undo/Redo功能的实现(7KB)&lt;END&gt;&lt;br&gt;40,40.zip Getting rid of Window ...

    windows 程序设计

    即使是在8088微处理器上跑的Windows 1.0也能进行这类内存管理。在实际模式限制下,这种能力被认为是软件工程一个令人惊讶的成就。在Windows 1.0中,PC硬件结构的640KB内存限制,在不要求任何额外内存的情况下被有效...

Global site tag (gtag.js) - Google Analytics