Post overriding the paint method of the components in java

a 夏天 提交于 2019-12-02 10:08:44

I have not tested this, but it seems like it would work. A JComponent's paint() method calls:

paintComponent(co);
paintBorder(co);
paintChildren(co);

where co is a Graphics object. In theory you create an image, retrieve the graphics object and then pass that into paintChildren(). you will have to call paintComponent() and paintBorder() yourself, if you do this. Then, just rotate the image and draw it into your component. You may have to crop the image or resize your component accordingly for this to work. It might look something like this:

BufferedImage myImage;

@Override
public void paint(Graphics g){
    myImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TRANSLUCENT);
    //using a transparent BufferedImage might not be efficient in your case
    Graphics myGraphics = myImage.getGraphics();
    super.paintComponent(g);
    super.paintBorder(g);
    super.paintChildren(myGraphics);
    //rotation code here
    //  ...
    //draw children onto your component
    g.drawImage(myImage, 0, 0,getWidth(), getHeight(), null);

}

I hope I didn't make any mistakes, please let me know if this works.

So basicaly what I want is that I throught the list of componets I have and say: "All of you (components) which are in the list will be rotated by some angle".

If you want to rotate panel and therefore all the components on the panel as a single using then you need to do the custom painting in the paintComponent() method.

If you want to rotate, for example, individual images that each have a different angle of rotation then you can again do this in the paintComponent(...) method and change the angle for each component.

Or, in this second case you can use the Rotated Icon class. In this case the Icon is just added to a JLabel. Then you can change the degrees of rotation and repaint the label, so there is no custom painting (except in the Icon itself).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!