gpt4 book ai didi

java - AWT 仅绘制最后添加的 Canvas

转载 作者:行者123 更新时间:2023-11-30 03:44:48 25 4
gpt4 key购买 nike

我有一个非常简单的 AWT 绘画。只是玩玩以做更大的事情。但无法让它工作......

发生的情况是只显示 elypse2 - 无论是否 repaint() 。

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

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

这是主函数:

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);
}
}
}

最佳答案

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

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

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);
}
}
}

关于java - AWT 仅绘制最后添加的 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26012093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com