java paint 覆盖,后覆盖在Java组件的paint方法

In java awt or swing when you want to change painting of some component you usually have to override the method paint(Graphics g) (in awt) or paintComponent(Graphics g) (in swing).

This is usually (maybe allways - I'm not sure) done when you are creating the component for example:

JPanel jPanel = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

//... my implementation of paint, some transfromations, rotation, etc

}

};

Imagine that you have container of components which could for example consists of some JLabels, some JTextFields, some image. Which will be all put on one component.

By container I mean you have some list or map with ids or some similar structure in which are all components you will put on one JFrame.

The question is if I can change the painting method after creating with all of the components which are in this list in the moment when all of them are already created. For example I want do the rotation action (rotate), which is defined in Graphisc2D, with all of them.

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". Is that possible? If yes how?

Edit:

This is my not correctly working solution:

graphicalDisplayPanel = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g2d = (Graphics2D) g;

g2d.rotate(Math.PI, anchorx, anchory);

}

@Override

public void paintChildren(Graphics g) {

super.paintChildren(g);

Graphics2D g2d2 = (Graphics2D) g;

g2d2.rotate(Math.PI, anchorx, anchory);

}

};

JFrame jFrame = JFrame();

// ... setting dimension, position, visible etc for JFrame, it works correctly nonrotated

jFrame.setContentPane(graphicalDisplayPanel);

解决方案

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值