我们刚刚从仅使用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);
}
}
的实际任务是绘制一个椭圆,填充黑色的背景,并把下面的标签。除了我的问题之外,是否有可能用颜色填充椭圆的背景,而不是首先绘制一个单独的矩形?
而不是使用绘画,你应该使用paintComponent。查看[执行自定义绘画](http://docs.oracle.com/javase/tutorial/uiswing/painting/) – MadProgrammer
为什么选择AWT而不是Swing?在[Swing extras over AWT]上看到这个答案(http://stackoverflow.com/a/6255978/418556)有很多很好的理由放弃使用AWT组件。如果您需要支持较老的基于AWT的API,请参阅[混合重量级和轻量级组件](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html)。 –