I want to create a dialogue with a customizable shape and transparency, think that the information bubble points to some component.
To do this, I add a JPanel to JDialog and overwrite the panel's paintComponent(Graphics) method. The panel itself contains regular JLabels and JButtons . Works great, but as soon as I use Graphics2D.setClip(Shape) in the panel drawing code, the components are overloaded with the background. If I do not set the clip (for a completely new Graphics2D object, not less), everything works fine. This is very puzzling to me, and I have no idea what I can do to fix it.
PS: I can not use setShape(Shape) in JDialog , because there is no smoothing. PPS: The actual Usecase is to draw a large background image that needs to be cropped exactly in the shape of an information bubble.
The following SSCCE demonstrates the problem when you press the "x" in the upper right corner several times.
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import java.awt.Polygon; import java.awt.Shape; public class Java2DTransparencySSCE extends JDialog { JPanel panel; private JButton close; private JLabel headline; private JLabel mainText; public Java2DTransparencySSCE() { setLayout(new BorderLayout()); setFocusable(false); setFocusableWindowState(false); setUndecorated(true); setBackground(new Color(0, 0, 0, 0)); panel = new JPanel(new GridBagLayout()) { @Override public void paintComponent(final Graphics g) { super.paintComponent(g); Graphics2D gImg = (Graphics2D) g.create();
EDIT: To get around this error on Windows, I added the following, which did not cause problems or performance impacts in my use case (may be different for you):
JDialog dialog = new Java2DTransparencySSCE() { @Override public void paint(Graphics g) { g.setClip(null); super.paint(g); } };
Marco source share