【问题标题】:How to create an image in Java SWT without display如何在 Java SWT 中创建不显示的图像
【发布时间】:2016-11-02 16:23:26
【问题描述】:

我正在学习 SWT,目标是创建一个向导。我正在修改现有教程。此时,我正在尝试在向导的一页中显示图像:

class FrontPage extends WizardPage {

  FrontPage() {
    super("FrontPage");
    setTitle("Listes des joueurs");
    setDescription("Veuillez déplacer toutes les listes dans le même fichier (ex: C:\\Badminton\\)");
  }

  public void createControl(Composite parent) {
    Composite composite = new Composite(parent, SWT.NULL);
    GridLayout gridLayout = new GridLayout(2, false);
    composite.setLayout(gridLayout);

    Canvas canvas = new Canvas(composite, SWT.NONE);
    canvas.setBounds(10, 10, 693, 253);

    canvas.addPaintListener(new PaintListener() {
      public void paintControl(PaintEvent e) {
        Image image = new Image(null, "C:\\Benoit\\Work\\Java\\Badminton\\Folder_List_Players.png");

        e.gc.drawImage(image, 10, 10);

        image.dispose();
      }
    });

    setControl(composite);

  }

}

运行此代码时,我的图像大约为 600 x 200,显示为缩略图 (10x10)。我想以全尺寸显示。

  1. 我知道我可能在 Image 构造函数中有一个 Display 对象,但我不确定如何使它与 Composite 父对象一起工作。然而有趣的是,我仍然能够使用 null Display 对象显示图像。

  2. canvas.setBounds(10, 10, 693, 253);似乎没有任何影响。

提前感谢任何提示或帮助!!!

【问题讨论】:

    标签: java swt


    【解决方案1】:

    如果使用 null Display 创建 Image,则使用当前 Display。为清楚起见,您应始终在创建图像时提供 Display。

    而且也不乏对当前显示的引用,例如:

    Display display = event.display;
    

    Display display = parent.getDisplay();
    

    为了显示图像,最好像这样使用Label

    Label imageLabel = new Label( parent, SWT.NONE );
    imageLabel.setImage( ... );
    

    要布局控件,请远离使用 setBounds() 和绝对坐标。改用布局管理器:https://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html

    【讨论】:

    • 非常感谢,我的图片现在可以正常显示了!
    • @BenoitGoderre Display.getCurrent()Display.getDefault() 是获取显示的其他方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2020-11-08
    • 2012-04-23
    相关资源
    最近更新 更多