Java 绘制简单图形的问题

2024-12-02 17:55:20
推荐回答(4个)
回答(1):

package org.swing.test;

import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import java.awt.Graphics;

class CircleComponent extends JComponent
{
public void paint(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
Ellipse2D.Double ellipse=new Ellipse2D.Double(100,100,100,100);
g2.setColor(Color.PINK);
g2.draw(ellipse);
g2.fill(ellipse);
Ellipse2D.Double ellipse2=new Ellipse2D.Double(150,150,50,50);
g2.setColor(Color.WHITE);
g2.draw(ellipse2);
g2.fill(ellipse2);

}

}

public class Test
{
public static void main(String args [])
{
JFrame frame=new JFrame();

final int FRAME_WIDTH=300;
final int FRAME_HEIGHT=300;
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

CircleComponent component=new CircleComponent();

frame.setContentPane(component);
frame.setVisible(true);
}
}

//-----直接运行就可以了

回答(2):

关键点就以下两个:
JFrame frame=new JFrame();
frame.add(component);

但是

circleComponent component=new circleComponent();

的过程中,没有执行他自己定义的drawComponent()方法。

也就是说,你填充的那个component 是一个空对象!

所以任何东西都看不到!

回答(3):

import javax.swing.JComponent;
import javax.swing.JFrame;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import java.awt.Graphics;

class circleComponent extends JComponent
{
public void drawComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
Ellipse2D.Double ellipse=new Ellipse2D.Double(100,100,100,100);
g2.setColor(Color.PINK);
g2.draw(ellipse);
g2.fill(ellipse);
Ellipse2D.Double ellipse2=new Ellipse2D.Double(150,150,50,50);
g2.setColor(Color.WHITE);
g2.draw(ellipse2);
g2.fill(ellipse2);
}
}
class ab
{
public static void main(String args [])
{
JFrame frame=new JFrame();
final int FRAME_WIDTH=300;
final int FRAME_HEIGHT=300;
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

circleComponent component=new circleComponent();
frame.add(component);
frame.setVisible(true);
}
}

回答(4):

关键在于frame.add()这个地方不对
JFrame的实际的容器是通过getContentPane()方法得到的,只有对这个得到的对象调用add()方法,才会被显示在frame里

frame.add(component); -》 frame.getContentPane().add(component);

就万事ok了