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?

DangerDan
  • 137
  • 1
  • 2
  • 14
  • Instead of using paint, you should use paintComponent. Check out [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) for more details – MadProgrammer Jun 11 '13 at 21:22
  • Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Jun 12 '13 at 16:07

1 Answers1

2

First of all when you override a method you should call parents method call cause u can break liskov substitution principle.

@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   
    } 

And the ellipse is not showing cause you never set a Layout, in your constructor you have to put something like this

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

And the result

frame result

NOTE You should not paint in top level containers , it is a good practice you to add your components for example in a Panel and override the paint method in the panel.

nachokk
  • 14,363
  • 4
  • 24
  • 53