JPanel问题上的Java Swing协调?

时间:2015-01-05 08:51:46

标签: java swing netbeans jpanel java-2d

我使用netbeans IDE创建Gui然后我自定义Jpanel2并在其上绘制多边形这是代码片段

  

int [] polygonXs = {151,153,158,159,154};
     int [] polygonYs = {6,1,3,8,10};
     Shape shape = new Polygon(polygonXs,polygonYs,polygonXs.length);

然后问题是点(151,6)(153,1)(158,3)(159,8)(154,10)在JFrame坐标中。
 另外现在(0,0)位于JFrame的左上角,但我希望(0,0)位于Jpanel2(黑色背景)的左上角。那么如何解决这个问题(图像下方的Jpanel2代码)。

This is jPanel2 class

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;

public class J2d1 extends JPanel{
public static final String TITLE = "Affine Transform Demo";

int[] polygonXs = { 151, 153, 158, 159, 154};
int[] polygonYs = { 6, 1, 3, 8, 10};
Shape shape = new Polygon(polygonXs, polygonYs, polygonXs.length);
double x = 50.0, y = 50.0;

public void paintComponent(Graphics g){
    super.paintComponent(g);
    setBackground(Color.BLACK);
    Graphics2D g2d = (Graphics2D)g;

    AffineTransform saveTransform = g2d.getTransform();
    AffineTransform identity = new AffineTransform();
    g2d.setTransform(identity);

    g2d.setColor(Color.green);
    g2d.fill(shape);
    g2d.translate(x, y);
    g2d.scale(2.2, 2.2);
    g2d.fill(shape);

    for(int i = 0; i < 5; ++i){
        g2d.translate(50.0, 5.0);
        g2d.setColor(Color.blue);
        g2d.fill(shape);
        g2d.rotate(Math.toRadians(15.0));
        g2d.setColor(Color.RED);
        g2d.fill(shape);            
    }
    g2d.setTransform(saveTransform);

    } 
}

1 个答案:

答案 0 :(得分:1)

使用SwingUtilities类。它有方法

public static Point convertPoint(Component source,Point aPoint,Component destination)
public static Point convertPoint(Component source,int x, int y,Component destination)

您可以在其中传递坐标并将一个组件的坐标转换为另一个组件坐标。