`
touchinsert
  • 浏览: 1329181 次
  • 性别: 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调用DLL方法 JAVA调用DLL方

    在Java中调用DLL文件主要通过Java Native Interface (JNI)、JAWINJNative和JNA等技术来实现。这些技术允许Java程序与本地代码进行交互,从而实现对DLL文件的调用。 #### JNI (Java Native Interface) JNI是Java...

    C#调用Java类的方法

    该过程需要借助IKVM(Java虚拟机)来实现。 标题:C#调用Java类的方法 描述: 本文将手把手地指导您如何在C#中调用Java类的方法。 标签: C#、Java类 知识点: 1. 将Java类文件打包为JAR文件 在将Java类文件打包为...

    android messagebox

    ```java public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //...

    MessageBox coding

    这个组件在各种编程语言和操作系统中都有相应的实现,如Windows API中的`MessageBox`函数,或者是Qt、WPF、WinForms等框架中的`MessageBox`类。在本文中,我们将深入探讨`MessageBox`的使用、功能、常见属性以及在...

    C#调用Java类的实现方法

    - 在C#的窗体应用程序中,通过事件触发(如Form1_Load事件),创建Java类的实例,并通过调用returnString方法后使用MessageBox显示返回的字符串。 7. **C#窗体应用程序示例**: - 在窗体加载事件中创建并使用Java...

    C++如何调用C# java

    在这篇文章中,我们将使用Visual Studio 2008作为开发工具,并使用C++/CLI(Common Language Infrastructure)来实现C++调用C#和Java语言的方法。 首先,我们需要添加Web引用。在Visual Studio 2008中,我们可以...

    java通过JNI调用dll的事例 附说明

    本教程将深入讲解如何使用Java通过JNI来调用DLL,并提供一个具体的实例——调用MessageBox函数。 首先,理解JNI的概念是至关重要的。JNI是Java平台标准的一部分,它为Java程序员提供了一种安全、高效的方式来调用...

    附录A 使用非JAVA代码.pdf

    例如,一个简单的Java程序可能会调用Windows API的`MessageBox()`函数,首先在Java中声明一个本地方法,然后用`javah`生成头文件,接着编写C代码实现这个方法,最后在Java代码中加载库。对于非Win32平台,可以替换为...

    LK-Bxx_JAVA_SDK.zip

    2. **TestPrint.class、MessageBox.class、TestPrint$KeyHandler.class**:这些都是编译后的Java类文件。`TestPrint`可能是一个主类,负责执行打印测试;`MessageBox`可能处理用户界面的弹窗显示;`TestPrint$...

    .net调用java WebService

    1. **添加Web服务引用**:在Visual Studio中打开.NET项目,通过“添加服务引用”功能,输入Java WebService的WSDL URL,即可自动生成所需的代理类。 - **步骤**: 1. 在解决方案资源管理器中右键点击项目名称...

    Jini实现步骤(如何实现JINI的Demon)

    **服务代理实现示例**:文件中提供了`TransferProxy`类,它是`Transfer`接口的一个实现。该类还实现了`ServiceIDListener`和`Serializable`接口。这里值得注意的是,`Serializable`接口确保了该类可以被序列化并通过...

    基于Tomcat7、Java、Ext、WebSocket的聊天室

    例如,你可以看到类名以`@ServerEndpoint`注解的Java类,这个注解是Java API for WebSocket (JSR 356) 提供的,用于定义WebSocket服务端点。 Ext是一个前端JavaScript框架,由Sencha公司开发,主要用来构建富客户端...

    利用java二次开发ug nx

    ### 利用Java进行UG NX的二次开发 ...总之,利用Java进行UG NX的二次开发是一种高效且灵活的方式,不仅能够充分利用Java的强大功能,还能充分利用UG NX的强大建模能力,从而实现更加复杂的自动化任务和定制化解决方案。

    SWT API JAVA

    5. **对话框和消息框**:SWT支持多种对话框,包括消息框(MessageBox)、打开/保存文件对话框(FileDialog)、颜色选择对话框(ColorDialog)等,这些都是日常应用中常用的交互元素。 6. **图像处理**:SWT提供了...

    java程序员笔试题.doc

    10. SWT与JFC/Swing:`MessageBox`、`MessageDialog`是SWT(Standard Widget Toolkit)中的类,而`JDialog`属于JFC/Swing包,`DisplayMode`是Java 2D图形中的类。 11. 合法标识符:Java中合法的标识符可以包含字母...

    图书管理系统用SWT做的JAVA图形化界面

    - 源代码结构:一个完整的SWT图书管理系统项目通常包含多个Java类,分别负责不同的功能,如主窗口类、数据库操作类、各个模块的UI类等。 - 资源管理:注意处理好图标、图片等资源的加载和释放,避免内存泄漏。 - ...

    extjs4.2+java经典

    成功或失败的结果将通过MessageBox显示给用户,其中包含了成功的消息或异常信息。 ### 关键概念 1. **数据绑定**:ExtJS中的数据绑定使得UI组件能够自动与模型数据保持同步。 2. **组件化**:ExtJS采用组件化的...

    Java程序设计之swt教程.rar

    3. **对话框(Dialogs)**:涵盖各种对话框的使用,如消息对话框 MessageBox、文件选择对话框 FileDialog、颜色选择对话框 ColorDialog等,以及如何创建自定义对话框。 4. **事件处理**:解释事件模型,如何注册事件...

Global site tag (gtag.js) - Google Analytics