swing事件里面改变swing界面

用Swing编写反应灵敏的图形用户界面
 
 
本文介绍如何使用Swing编写反应灵敏的图形用户界面。

正文

不灵敏的图形用户界面会降低应用程序的可用性。当以下现象出现的时候,我们通常说这个用户界面反应不灵敏。

  1. 不响应事件的现象;
  2. 没有更新的现象;

这些现象在很大程度上与事件的处理方法相关,而在编写Swing应用程序的时候,我们几乎必然要编写方法去响应鼠标点击按钮,键盘回车等事件。在这些方法中我们要编写一些代码,在运行时去触发一些动作。常见动作包括查找,更新数据库等。在这篇文章中通过对一个实例的分析,介绍了一些基本概念,常见的错误以及提出了一个解决方案。

event-dispatching thread

我们一定要记住,事件响应方法的代码都是在event-dispatching thread中执行的,除非你启用另一个线程。

那么,什么是event-dispatching thread呢?在《Java Tutorial》[1]中,作者给出了一条单一线程规则:一旦一个Swing组件被实现(realized),所有的有可能影响或依赖于这个组件的状态的代码都应该在event-dispatching thread中被执行。而实现一个组件有两种方式:

  1. 对顶层组件调用show(), pack(), 或者setVisible(true);
  2. 将一个组件加到一个已经被实现的容器中。

单一线程规则的根源是由于Swing组件库的大部分方法是对多线程不安全的,尽管存在一些例外。这些例外的情况可以在《Java Tutorial》[1]的相关章节找到,这里不再展开。

为了支持单一线程模型,Swing组件库提供了一个专门来完成这些与Swing组件相关的操作的线程,而这一线程就是event-dispatching thread。我们的事件响应方法通常都是由这一线程调用的,除非你自己编写代码来调用这些事件响应方法。在这里初学者经常犯的一个错误就是在事件响应方法中完成过多的与修改组件没有直接联系的代码。其最有可能的效果就是导致组件反应缓慢。比如以下响应按钮事件的代码:

String str = null;
this.textArea.setText("Please wait...");
try {
    //do something that is really time consuming
    str = "Hello, world!";
    Thread.sleep(1000L);
} catch (InterruptedException e) {
    e.printStackTrace();
}
this.textArea.setText(str);	

执行之后的效果就是按钮似乎定住了一段时间,直到Done.出现之后才弹起来。原因就是Swing组件的更新和事件的响应都是在event-dispatching thread中完成的,而事件响应的时候,event-dispatching thread被事件响应方法占据,所以组件不会被更新。而直到事件响应方法退出时才有可能去更新Swing组件。

为了解决这个问题,有人也许会试图通过调用repaint()方法来更新组件:

final String[] str = new String[1];
this.jTextArea1.setText("Please wait...");
this.repaint();
        
try {
    Thread.sleep(1000L);
}catch(InterruptedException e) {
    e.printStackTrace();
}
str[0] = "Done.";

jTextArea1.setText(str[0]);

但是这一个方法没有起到预期的作用,按钮仍然定住一段时间,在察看了repaint()方法的源代码之后就知道原因了。

PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
    new Rectangle(x, y, width, height));
Toolkit.getEventQueue().postEvent(e);		

repaint()方法实际上是在事件队列里加了一个UPDATE的事件,而没有直接去重画组件,而且这一个事件只能等待当前的事件响应方法结束之后才能被分配。因此只有绕过分配机制直接调用paint方法才能达到目的。

final String[] str = new String[1];
this.jTextArea1.setText("Please wait...");
this.paint(this.getGraphics());
        
try {
    Thread.sleep(1000L);
}catch(InterruptedException e) {
    e.printStackTrace();
}
str[0] = "Done.";

jTextArea1.setText(str[0]);

这样却是实现了更新,但是还存在着以下的问题。虽然从感觉上,按钮已经弹起来了,但是在Done.出现之前,我们却无法按下这个按钮。可以说按钮还是定住了,只不过定在了弹起的状态。调用重绘方法无法从根本上解决问题,因此我们需要寻求其他的方法。

使用多线程

有效的解决方法是使用多线程。首先看一看一个更好的解决方案,这一方案是在参考《Rethinking Swing Threading》[3]的一个程序片段完成的:

final String[] str = new String[1];
this.jTextArea1.setText("Please wait...");
this.repaint();
        
new Thread() {
    public void run() {
        try {
            Thread.sleep(1000L);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
        str[0] = "Done.";
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                jTextArea1.setText(str[0]);
             }
        });
    }
}.start();

在这个程序中,要花费大量时间的操作被放到另一个线程当中,从而使事件响应方法能快速返回,event-dispatching thread就可以更新UI和响应其它事件了。注意到这个程序使用了invokeLater()方法。invokeLater()方法的作用是让event-dispatching thread去运行制定的代码。当然也可以不使用invokeLater()方法,但是这样就违背了单一线程原则,同时带来了一定程度的相对多线程的不安全性。到现在,解决方案似乎是完美的了,但是我们看一看在原来的程序添加下面的代码,尽管我们通常不这样做。

public void paint(java.awt.Graphics g) {
    super.paint(g);
    g.drawRect(1, 1, 100, 100);
}

我们会发现以前画的矩形被覆盖了一部分,原因是由于我们没用重画这一个矩形,因此在结尾加上对repaint()方法的调用。

final String[] str = new String[1];
this.jTextArea1.setText("Please wait...");
this.repaint();
        
new Thread() {
    public void run() {
        try {
            Thread.sleep(1000L);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
        str[0] = "Done.";
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                jTextArea1.setText(str[0]);
                repaint();
             }
        });
    }
}.start();

如果你认为这段代码过于缺乏可读性,通过在《Java Tutorial》[1]里面介绍的SwingWorker来简化编程的方法。可以通过实现一个construct()方法来实现花费大量时间的操作和重写finished()方法来完成组件更新的工作。

this.jTextArea1.setText("Please wait...");
        
final SwingWorker worker = new SwingWorker() {
    public Object construct() {
        try {
            Thread.sleep(1000L);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
        return "Done.";
    }
    public void finished() {
        jTextArea1.setText(getValue().toString());
        repaint();
    }
};
worker.start();

在《Rethinking Swing Threading》[3],作者将以上的编程方式称为同步方式。另外作者提出了一个通过消息机制来实现相同功能的更清晰,但是需要编写更多代码的"异步"的方法。

结论

总之,我们在编写使用Swing组件的程序是要记住以下几点:

1、不要过多地占用event-dispatching thread;

2、与更新组件相关的代码要使用event-dispatching thread去执行;

3、要更新组件。

编写反应灵敏的图形用户界面还需要考虑很多问题,以上只是最基本的一部分。欢迎有兴趣的读者来信进行讨论

 

 

 

 

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame7.java
 *
 * Created on 2010-4-8, 10:42:52
 */

package javaapplication1;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;

/**
 *
 * @author aken
 */
public class NewJFrame7 extends javax.swing.JFrame {

   
    /** Creates new form NewJFrame7 */
    public NewJFrame7() {
        initComponents();
      
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon("C://Documents and Settings//aken//桌面//loadingbar.JPG")); // NOI18N
        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addComponent(jButton1)
                .addGap(89, 89, 89)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(125, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(93, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(116, 116, 116))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(105, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        th t=new th(this.jLabel1,this.jButton1);
        jLabel1.setIcon(new javax.swing.ImageIcon("C://Documents and Settings//aken//桌面//loadingbar.gif"));
        t.start();
        this.jButton1.setEnabled(false);
       

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame7().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

   

}
class th extends Thread{

    javax.swing.JLabel jLabel1 ;
    javax.swing.JButton button;
    public th(javax.swing.JLabel jLabel1,javax.swing.JButton button){
        this.jLabel1=jLabel1;
        this.button=button;
    }

    public void run(){
        /*处理业务逻辑
        int i=0;
        while(i<5){
            try {
                Thread.sleep(1000l);
                i++;
            } catch (InterruptedException ex) {
                Logger.getLogger(th.class.getName()).log(Level.SEVERE, null, ex);
            }
        }*/
        jLabel1.setIcon(new javax.swing.ImageIcon("C://Documents and Settings//aken//桌面//loadingbar.JPG"));
        button.setEnabled(true);
    }
   
   

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值