AWT涂料最后添加了Canvas

时间:2014-09-24 08:27:09

标签: java swing awt

我有一个非常简单的AWT绘画。只是为了让一些更大的东西发挥作用。但是无法让它发挥作用......

只会显示elypse2 - 无论是否重画(),都会发生。

我也尝试使用Swing组件而不是AWT(JFrame,JComponent),但这也没有改变。

是否需要使用布局管理器?但我想只绘制图形组件,如弧形,矩形,直线,多边形线,等等......

这是main():

public static void main(String[] args) {
  Frame testFrame = new Frame("Grafx-Test");
  testFrame.setSize(300, 200);
  testFrame.setAlwaysOnTop(true);

  java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
      testFrame.setVisible(true);
    }
  });

  Elypse elypse = new Elypse(new Point(70, 80), 30, 30, Color.BLUE, false);
  testFrame.add(elypse);

  Elypse elypse2 = new Elypse(new Point(70, 50), 50, 30, Color.BLUE, true);
  testFrame.add(elypse2);
}

这里使用的类:

public class Elypse extends Canvas {

  private Point start;
  private int width;
  private int height;
  private Color c;
  private boolean filled;

  public Elypse(Point start, int width, int height, Color c, boolean filled) {
    this.start = start;
    this.width = width;
    this.height = height;
    this.c = c;
    this.filled = filled;
  }

  @Override
  public void paint(Graphics g) {
    g.setColor(c);
    if (filled) {
      g.fillOval(start.x, start.y, width, height);
    }
    else {
      g.drawOval(start.x, start.y, width, height);
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您忽略了pack()封闭的Window。请注意原始代码中的特征症状:调整生成更新的框架大小会导致elypse2出现。

附录:您可以使用Elypse等布局查看两个 GridLayout个实例。

testFrame.setLayout(new GridLayout(0, 1));

image

经测试:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;

public class Test {

    public static void main(String[] args) {
        Frame testFrame = new Frame("Grafx-Test");
        testFrame.setAlwaysOnTop(true);
        Elypse elypse = new Elypse(new Point(70, 80), 30, 30, Color.BLUE, false);
        testFrame.add(elypse);
        Elypse elypse2 = new Elypse(new Point(70, 50), 50, 30, Color.BLUE, true);
        testFrame.add(elypse2);
        testFrame.pack();
        testFrame.setVisible(true);
    }

    private static class Elypse extends Canvas {

        private Point start;
        private int width;
        private int height;
        private Color c;
        private boolean filled;

        public Elypse(Point start, int width, int height, Color c, boolean filled) {
            this.start = start;
            this.width = width;
            this.height = height;
            this.c = c;
            this.filled = filled;
        }

        @Override
        public void paint(Graphics g) {
            g.setColor(c);
            if (filled) {
                g.fillOval(start.x, start.y, width, height);
            } else {
                g.drawOval(start.x, start.y, width, height);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(320, 240);
        }
    }
}