在AWT中的GUI操作在AWT中不是SWING

时间:2017-01-08 16:29:06

标签: java canvas awt event-dispatch-thread

问题是是否可以安全地从主线程(即外部事件派发线程)调用java.awt.Canvas.setBackground(Color)而没有崩溃的风险。

背景

我正在起草关于有限自动机的本科学生,并寻求一种可视化他们行为的方法。我不想分散我的学生的注意力。通过线程问题来关注主题。 在设置和更改GUI时,Java Swing需要有关线程的预防措施,请参阅:

所以Swing在这个阶段似乎不是一个选择。上面的文章似乎关注Swing而不是AWT。至于AWT,我读了

有希望的陈述

  

AWT组件旨在是线程安全的

问题重新措辞

AWT文档中是否记录了足够的线程安全性,以便我可以将它依赖于所有JRE中的Canvas类?

演示代码示例

我所说的与AWT相关的代码就像Colours.java中的以下颜色转换器一样简单:

 import java.awt.Frame;
 import java.awt.Canvas;
 import java.awt.Color;

 /** Demonstrates Java AWT operated from main thread. */
 public class Colours {
    private static final Color[] colours = {
       Color.RED, Color.GREEN, Color.BLUE
    };
    public static void main ( final String[] arguments ) {
       final Frame frame = new Frame( "Colours" );
       final Canvas canvas = new Canvas();
       frame.setSize( 320, 200 );
       frame.add( canvas );
       frame.setVisible( true );
       final ExitListener exitListener = new ExitListener();
       frame.addWindowListener( exitListener );
       int choice = 0;
       while ( ! exitListener.isExiting() ) {
          canvas.setBackground( colours[choice] );
          if ( ++choice >= colours.length ) {
             choice = 0;
          }
          try {
             Thread.sleep( 1000 );
          } catch ( final InterruptedException e ) {}
       }
    }
 }

ExitListener.java

 import java.awt.Window;
 import java.awt.event.WindowEvent;
 import java.awt.event.WindowListener;

 public class ExitListener implements WindowListener {

    private boolean isExiting = false;

    public boolean isExiting () {
       return isExiting;
    }

    @Override
    public void windowActivated ( final WindowEvent e ) {}

    @Override
    public void windowClosed ( final WindowEvent e ) {}

    @Override
    public void windowClosing ( final WindowEvent e ) {
       isExiting = true;
       final Window window = e.getWindow();
       window.dispose();
    }

    @Override
    public void windowDeactivated ( final WindowEvent e ) {}

    @Override
    public void windowDeiconified ( final WindowEvent e ) {}

    @Override
    public void windowIconified ( final WindowEvent e ) {}

    @Override
    public void windowOpened ( final WindowEvent e ) {}
 }

N.B。:java.awt.event.WindowAdapter没有被故意使用,因为国家的继承将在课程的后期进行讨论。

0 个答案:

没有答案