【问题标题】:Display label and shape at the same time同时显示标签和形状
【发布时间】:2013-06-12 08:10:45
【问题描述】:

我们刚刚开始仅使用 AWT 在 Java 中进行 GUI 编程。我的任务是绘制一个椭圆并将其与标签一起显示。不知何故,我无法弄清楚如何同时显示它们。只要我添加

add(label);

对于我的程序,它只显示标签。 到目前为止,这就是我的代码......

import java.awt.*;
public class Ellipse extends Frame{

public static void main (String args[]) {
    new Ellipse("Ellipse");
}

public void paint(Graphics g){
    Graphics shape = g.create();
    shape.setColor(Color.black);
    shape.fillRect(100,80,100,40);
    shape.setColor(Color.red);
    shape.fillOval(100,80,100,40);

} 

Ellipse(String s){
        super(s);
        setLocation(40,40);
        setSize(300,300);
        setBackground(Color.white);
        Font serif = new Font("Serif", 1, 10);
        setFont(serif);
        Label label = new Label("Ellipse 1",1);
        add(label);
        setVisible(true);
}
}

实际的任务是画一个椭圆,用黑色填充背景并在下面放一个标签。除了我的问题之外,除了先绘制一个单独的矩形之外,是否有可能用颜色填充椭圆的背景?

【问题讨论】:

标签: java awt


【解决方案1】:

首先,当您覆盖一个方法时,您应该调用父方法调用,因为您可能会破坏 liskov 替换原则。

@Override
    public void paint(Graphics g){
        super.paint(g);
        Graphics shape = g.create();
        shape.setColor(Color.black);
        shape.fillRect(100,80,100,40);
        shape.setColor(Color.red);
        shape.fillOval(100,80,100,40);
        shape.dispose();// And if you create it, you should dispose it   
    } 

椭圆没有显示,因为你从来没有设置布局,在你的构造函数中你必须放这样的东西

    Ellipse(String s){
        super(s);
        setLocation(40,40);
        setLayout(new FlowLayout());
        setSize(300,300);
        setBackground(Color.white);
        Font serif = new Font("Serif", 1, 10);
        setFont(serif);
        Label label = new Label("Ellipse 1",1);
        add(label);
        pack(); // size the frame
        setVisible(true);
}

结果

注意您不应该在顶级容器中绘制,最好将组件添加到 Panel 中并覆盖面板中的绘制方法。

【讨论】:

  • 如果你创建它,你应该处理它(即图形)
  • 建议在油漆上使用paintComponent(根据我对问题的评论),你正在走向一个成功的问题;)
  • @MadProgrammer 但那是用于摆动组件还是也用于 awt?因为他正在使用所有 awt
  • 啊,对不起,错过了他覆盖Frame,那么OP应该避免覆盖顶级容器上的paint:P
  • 非常感谢。您可以建议任何仅 AWT 的教程吗?到目前为止我发现的大多数也使用摇摆......
猜你喜欢
  • 2021-02-07
  • 2018-07-24
  • 2018-05-28
  • 2021-07-19
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
相关资源
最近更新 更多