简体   繁体   English

如何在JPanel上绘制矩形?

[英]How to draw a rectange on top of JPanel?

I want to draw a rectange on top of JPanel . 我想在JPanel上绘制一个矩形。 Next I want to set proper location for this rectangle. 接下来,我想为此矩形设置适当的位置。 This is how I do this. 这就是我的方法。 I tried to change number in g.fillRect(margin, margin, 30, 30) , but my rectangle is always located in the center of JPanel . 我试图在g.fillRect(margin, margin, 30, 30)更改数字,但是我的矩形始终位于JPanel的中心。 Why? 为什么?

JPanel chartPanel = new JPanel();

// here we add components to chartPanel
// ...

chartPanel.add(new LegoBox());

class LegoBox extends JPanel {

    public void paintComponent(Graphics g) {
            super.paintComponent(g);
            int margin = 0;          
            g.setColor(Color.red);
            g.fillRect(margin, margin, 30, 30);
    }
}

Perhaps it is the LayoutManager from chartPanel ? 也许是chartPanelLayoutManager
For reproducing your problem you have to post a working example. 为了重现您的问题,您必须发布一个有效的示例。
Try filling the chartPanel with you custom panel: 尝试使用自定义面板填充chartPanel

chartPanel.setLayoutManager(new BorderLayout());
chartPanel.add(new LegoBox(), BorderLayout.CENTER); 

paintComponent: paintComponent:

super.paintComponent(g);
g.setColor(Color.red);
int rectWidth = 30;
int rectHeight = 30; 
int marginLeft = 12; // a pixel value
int marginTop = 17;      
g.fillRect(marginLeft, marginTop, rectWidth, rectHeight);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM