在JPanel的中心添加一个矩形

时间:2015-01-21 08:14:32

标签: java swing jpanel rectangles

我试图将Rectangle绘制到JPanel的中心。我已经制作了这段代码,但是当我运行它时,矩形不会出现在面板中。如果我尝试使用JFrame,则会出现矩形。有人能帮助我吗?

RectangleTester

package eventi5;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class RectangleTester {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Rectangle");
        frame.setSize(250, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final RectangleComponent component = new RectangleComponent();
        frame.setVisible(true);
        JPanel panel=new JPanel();
        panel.add(component);
        frame.add(panel);
    }
}

RectangleComponent

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JPanel;

public class RectangleComponent extends JPanel{

    private Rectangle box;

    public RectangleComponent(){
        box=new Rectangle(10,20,30,40);
    }

      public void paintComponent(Graphics g){
        Graphics2D g2=(Graphics2D) g;
        g2.draw(box);
        g2.setColor(Color.BLUE);
        g2.fill(box);
    }   
}

1 个答案:

答案 0 :(得分:3)

1)您需要覆盖getPreferedSize()的{​​{1}},例如下一个:

RectangleComponent

2)在自定义之前调用 @Override public Dimension getPreferredSize() { return new Dimension(box.width+box.x*2,box.height+box.y*2); } super())的paintComponent()方法。

编辑:

super.paintComponent(g);