2012-01-04 28 views
3

JavaでGraphicsをつかんで、JPanelでサークルを作成しました。 JPanelの円の中心をどのようにしますか?パネルの中央に画像を配置する

package exerciseninetwo; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.geom.Ellipse2D;  

public class ExerciseNineTwo extends JFrame 
{ 
    public ExerciseNineTwo() 
    { 
     super("My Frame"); 
     setSize(500, 500); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     add(new CanvasPanel()); 

     setVisible(true);   
    }   

    public static void main(String[] args) 
    { 
     new ExerciseNineTwo(); 
    } 
} 
class CanvasPanel extends JPanel 
{   
    CanvasPanel() 
    { 
     setSize(120, 120);    
     //setBackground(Color.cyan); 
    } 

    protected void paintComponent(Graphics g) 
    { 
     Graphics2D comp = (Graphics2D)g; 
     Ellipse2D circle = new Ellipse2D.Float(200, 200, 200, 200); 
     comp.draw(circle); 

     comp.setColor(Color.cyan); 
     comp.fillRect(0,0,500,500); 

     comp.setClip(circle); 
     comp.setColor(Color.magenta); 
     comp.fillRect(0,0,500,500);   
    } 
} 
+0

'ExerciseNineTwo'この[タグ:宿題]ですか? –

+0

あなたの質問とは無関係に、CanvasPanelへのいくつかのコメント:a)paintComponentの実装は、サイズが> 500,500(修復するには_always_ super.paintComponentを呼び出します)の場合、superの不透明なコントラクトに違反します。b) (実際のサイジングは、親のレイアウトマネージャの仕事です) – kleopatra

答えて

5

のコンストラクタで、xとyを設定します。

float x = getWidth()/2 - ELLIPSE_WIDTH/2; 
float y = getHeight()/2 - ELLIPSE_HEIGHT/2; 
Ellipse2D circle = new Ellipse2D.Float(x, y, ELLIPSE_WIDTH, ELLIPSE_HEIGHT); 
+0

+1私のものより少し前です。 – StanislavL

+0

私は今それを得る。ありがとうございます。 – Arianule

3

パネルオブジェクトを取得し、XおよびYサイズパラメータ(または幅と高さ)を照会します。それぞれを2で割ると、フレームの中心が得られます。結果をX座標とY座標として使用して円を作成します。

float x = (width-width of oval) /2; 
float y = (height-height of oval) /2; 

よう

は今ちょうどあなたのパネルの真ん中にそれを描く日食

3

パネルのgetWidth()/getHeight()を使用してください。

int x=(getWidth()-ovalWidth)/2; 
int y=(getHeight()-ovalHeight)/2; 

パネルの幅が楕円形の幅より大きく、高さが同じであることを確認します。

2

あなたが簡単にパネルのサイズを取得し、それに応じて円を置くことがあります。

Dimension size = getSize(); 
Ellipse2D circle = new Ellipse2D.Float(
    (size.width - 200)/2,  // -200 due to the width/height of the circle 
    (size.height - 200)/2, 
    200, 200); 
関連する問題