I have developed a swing application with an oval and a button whose output is shown below and the code follows :-
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With