Need help understanding turn code

I developed a rotation application with an oval and a button, the output of which is shown below, and the code is as follows: -

enter image description here

Code: -

import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class AlphaCompositeDemo extends JFrame{ AlphaCompositeDemo() { super("AlphaComposite Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400,400); setLayout(new FlowLayout()); setBackground(new Color(0.2f,0.7f,0.1f,0.4f)); comp c=new comp(); add(c); add(new JButton("Click")); setVisible(true); } public static void main(String args[]) { JFrame.setDefaultLookAndFeelDecorated(true); SwingUtilities.invokeLater(new Runnable(){public void run(){new AlphaCompositeDemo();}}); } } class comp extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2=(Graphics2D)g.create(); g2.setComposite(AlphaComposite.SrcOver); g2.setColor(Color.RED); g2.fillOval(50, 50, 220, 120); } public Dimension getPreferredSize() { return new Dimension(200,200); } } 

Now I have the following questions:

  • If I specified the x, y coordinates for the oval, then why does it move from its position when the window is resized? (Although I know that due to FlowLayout, it is centered, but then it violates the property, which needs to be fixed, since I specified the x, y coordinates).
  • Secondly, if the conclusion is obvious (which I did not expect), then the x, y coordinates that I indicated were wrt, in which corner?
+4
source share
2 answers

The coordinates you specify are inside your own "component", and not inside the "parent" container.

It is probably easier to understand if you change add the following line to the paintComponent method:

 g2.drawRect( 0,0, 199, 199 ); 

The rectangle corresponds to the return of preferredSize . You see that this rectangle is always drawn and moves when the window is resized. The oval remains in the same relative position inside the rectangle.

Note that the size returned in getPreferredSize is smaller than the actual size of what you are trying to draw. This explains why you only see part of the oval.

+6
source

Q1 , putting your oval in coordinates 50, 50. You do not center your oval.

from javadoc

try to get the center of your frame first with getWidth() and getHeight() , and then use this as values โ€‹โ€‹for the center of your oval.

Sort of:

 g2d.fillOval(frame.getHeight()/2, frame.getWidth()/2, 200, 200); 

Q2 coordinates start from the upper left corner

+2
source

Source: https://habr.com/ru/post/1442341/


All Articles