程序运行后的效果图
程序代码
import java.util.Vector;
public class
Bottle
{ //容器类
private static int MaxCapacity = 100; //设置容器最大值
public static int getMaxCapacity() {
return MaxCapacity;
}
private int capacity = 0;
private Vector waterListeners = new Vector(); //对象数组
public synchronized int fillWater(int quantity) { //序列化(用于多线程)
if (this.capacity == getMaxCapacity() / 2) {
WaterEvent weh = new WaterEvent(this.capacity);
this.fireWaterHalf(weh);
}
this.capacity = this.capacity + quantity; //当前的注水量
if (this.capacity > getMaxCapacity()) { //判断水是否溢出
WaterEvent we = new WaterEvent(this.capacity);
this.fireWaterOverflowed(we);
}
return this.capacity;
}
public synchronized void addWaterListener(WaterListener wl) { //添加监听并且序列化
waterListeners.addElement(wl);
}
public int getCapatity() {
return this.capacity;
}
public void fireWaterHalf(WaterEvent we) {
Vector o;
synchronized (this) {
o = (Vector) waterListeners.clone();
for (int i = 0; i < o.size(); i++) {
((WaterListener) o.elementAt(i)).waterHalffolwed(we);
}
}
}
public void fireWaterOverflowed(WaterEvent we) {
Vector o;
synchronized (this) {
o = (Vector) waterListeners.clone();
for (int i = 0; i < o.size(); i++) {
((WaterListener) o.elementAt(i)).waterOverflowed(we);
}
}
}
}
//事件类
import java.util.*;
public classWaterEventextendsEventObject{
private int capacity;
public WaterEvent(int capacity) {
super(capacity);
this.capacity = capacity;
}
public int getCapacity() {
return this.capacity;
}
}
// 定义接口
import java.util.EventListener;
public interfaceWaterListener extendsEventListener{ //监听器
public void waterOverflowed(WaterEvent we); //水溢出
public void waterHalffolwed(WaterEvent we); //水达到一半
}
//实现接口中的方法
import java.util.*;
import javax.swing.JOptionPane;
public classWaterEventExcuteimplemesWaterListener{ //事件处理
public void waterOverflowed(WaterEvent we) {
JOptionPane.showMessageDialog(null, "注水已经达到了最大容量!不可以在加水了!");
}
public void waterHalffolwed(WaterEvent we) {
JOptionPane.showMessageDialog(null, "注水已经达到一半请注意加水!");
}
}
//测试类
(这里是直接使用NetBeans开发工具拖出来的界面)
package eventdemo;
import javax.swing.JOptionPane;
public classTestextends javax.swing.JFrame implements Runnable { Bottle b; int quantity; Thread thread; public Test() { initComponents(); b = new Bottle(); b.addWaterListener(new WaterEventExcute()); } public void startThread() { thread = new Thread(this); thread.start(); } public void stopThread() { thread.stop(); } /*public void waterHalffolwed() { JOptionPane.showMessageDialog(null, "注水已经达到一半请注意加水!"); }*/ public void run() { int quantity = 10; while (true) { try { int c = b.fillWater(quantity); this.lblQuantity.setText(String.valueOf(b.getCapatity())); if (c > Bottle.getMaxCapacity()) { break; } Thread.sleep(100); } catch (Exception e) { } } } /** * Creates new form Test */ /** * 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") // private void initComponents() { jLabel1 = new javax.swing.JLabel(); lblQuantity = new javax.swing.JLabel(); btnStart = new javax.swing.JButton(); btnStop = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("当前注水量为:"); lblQuantity.setText("0"); btnStart.setText("开始"); btnStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStartActionPerformed(evt); } }); btnStop.setText("停止"); btnStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStopActionPerformed(evt); } }); 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(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(btnStart) .addGap(18, 18, 18) .addComponent(btnStop)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(lblQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(204, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(lblQuantity)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnStart) .addComponent(btnStop)) .addContainerGap(25, Short.MAX_VALUE)) ); pack(); }// private void btnStartActionPerformed(java.awt.event.ActionEvent evt) { try { startThread(); } catch (Exception e) { } } private void btnStopActionPerformed(java.awt.event.ActionEvent evt) { try { stopThread(); } catch (Exception e) { } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Test().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnStart; private javax.swing.JButton btnStop; private javax.swing.JLabel jLabel1; private javax.swing.JLabel lblQuantity; // End of variables declaration }