[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]使用LinkedBlockingQueue写的消息中心

上一篇:[备忘]pojo与xml互相转换的类库,XStream
下一篇:[备忘]Swing的JTextArea自动滚动到底部

添加日期:2013/5/17 16:36:58 快速返回   返回列表 阅读5096次
总需要用,总是重写,赶紧备份。
------------------------------------------
消息中心
MsgCenter.java


import java.util.concurrent.LinkedBlockingQueue;

/**
 * 消息中心.
 */
public class MsgCenter {

    /**
     * 消息结束符,收到此消息,认为执行结束.
     */
    public static final String END_STR = "--end--";

    /**
     * 消息队列,本身是线程安全的.
     */
    private static final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

    /**
     * 放入一条消息.
     * 
     * @param msg
     *            消息内容
     */
    public static void putMsg(final String msg) {
        if (msg == null) {
            return;
        }

        try {
            queue.put(msg);
        } catch (InterruptedException e) {
        }
    }

    /**
     * 取一条消息.
     * 
     * @return 消息内容
     */
    public static String takeMsg() {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            return "";
        }
    }

    /**
     * 清空消息.
     */
    public static void clear() {
        queue.clear();
    }

    /**
     * 打开消息对话框.
     */
    public static void showMsgDialog() {

        // 由于MsgDialog里设置为了模态窗口,导致new MsgDialog()后面的代码不会执行(关闭窗口后才会执行),
        // 所以用一个线程来new对话框.
        new Thread(new Runnable() {

            @Override
            public void run() {
                new MsgDialog().setVisible(true);
            }
        }).start();

        // 休眠半秒,确保消息框先弹出来.
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }
    }

}



写了个对话框,从消息中心取消息,并显示.


import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

/**
 * 从消息中心取得消息并显示的对话框(模态的).
 * 
 */
public class MsgDialog extends JDialog {

    private static final long serialVersionUID = 4906144699636471579L;

    private final JPanel contentPanel = new JPanel();

    // 显示消息的文本框
    private JTextArea msgArea;

    // 取消息的线程
    private Thread msgThread = null;

    // 是否正在运行
    private boolean isRunning = false;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            MsgDialog dialog = new MsgDialog();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the dialog.
     */
    public MsgDialog() {
        setModalityType(ModalityType.APPLICATION_MODAL);
        setAlwaysOnTop(true);
        setTitle("执行控制台");
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        setResizable(false);
        setSize(450, 300);
        setLocationRelativeTo(null);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(new BorderLayout(0, 0));
        {
            msgArea = new JTextArea();
            msgArea.setEditable(false);
            contentPanel.add(msgArea);
        }
        {
            JLabel lblNewLabel = new JLabel("消息:");
            contentPanel.add(lblNewLabel, BorderLayout.NORTH);
        }
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton okButton = new JButton("关闭");
                okButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        // 没有结束,不允许关闭
                        if (isRunning) {
                            JOptionPane.showMessageDialog(MsgDialog.this,
                                    "正在执行,不能关闭。");
                            return;
                        }
                        msgThread.interrupt(); // 中断线程.
                        MsgDialog.this.dispose(); // 哈哈,想了半天,这么最简单。
                    }
                });
                okButton.setActionCommand("OK");
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);
            }
        }

        getMsg();
    }

    /**
     * 取消息.
     */
    private void getMsg() {

        // 开始运行啦~~
        isRunning = true;

        // 自动启动取消息的线程
        msgThread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        // 取一条消息,没有则等待
                        final String msg = MsgCenter.takeMsg();

                        // 消息不为空
                        if (msg != null && msg.length() > 0) {

                            // 取到结束符,则结束线程
                            if (msg.equals(MsgCenter.END_STR)) {
                                break;
                            } else {
                                // 传递给文本框显示
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        msgArea.append(msg + "\n"); // append方法线程安全.
                                    }
                                });
                            }
                        }

                        // 休息一会
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // 被中断,退出循环
                        break;
                    }
                }
                // 运行结束
                isRunning = false;
            }
        });
        msgThread.start();
    }

}



使用方法:


MsgCenter.clear(); //清空消息
MsgCenter.showMsgDialog(); //打开消息对话框

...做一些事情
MsgCenter.putMsg("什么什么");

...做一些事情
MsgCenter.putMsg("什么什么");

MsgCenter.putMsg("xxx完毕。");
MsgCenter.putMsg(MsgCenter.END_STR);

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved