0

We just started with GUI Programming in Java using AWT only. My task is to draw an ellipse and display it together with a label. Somehow I can't figure out how to display them at the same time. As soon as I add

add(label);

to my program it only displays the label. Thats my code so far...

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

The actual task is to draw an ellipse, fill the background with black and put a label below. Besides my problem, is there a possibility to fill the background of the oval with color other than drawing a seperate rectangle first?

4

1 回答 1

2

首先,当您覆盖一个方法时,您应该调用父方法调用,因为您可以打破 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);
}

结果

帧结果

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

于 2013-06-11T20:34:39.303 回答