Question

I have developed a swing application with an oval and a button whose output is shown below and the code 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:

  1. If I have specified the x,y coordinates for oval,then why it moves from its position when window is resized? (Though I know that due to FlowLayout it is aligned at centre but it then violates the property that it must be fixed as i have specified coordinates x,y).
  2. Secondly if the output is obvious (which I was not expecting) then x,y coordinates that I specified was w.r.t which corner?
Was it helpful?

Solution

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

Probably easier to understand if you change add the following line to the paintComponent method:

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

The rectangle matches the preferredSize you return. You see that this rectangle is always drawn, and moves when resizing the window. The oval stays at the same relative position inside the rectangle.

Note that the size you return in getPreferredSize is smaller then the actual size of what you try to paint. That explains why you only see part of the oval

OTHER TIPS

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

from the javadoc

try getting the center of your frame first with getWidth() and getHeight() and then use that as values for the center of your oval.

Something like:

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

Q2 coordinates starts from upper left corner

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top