Search code examples
javaswingjfreechartjcomponent

Add Multiple transparent JComponents objects to just one JPanel


This problem is bothering me a lot.

Suppose I have two different classes called DrawProfile and PlotData. These classes extend JComponent. I have also a JPanel called profile. I want to add first the DrawProfile to my profile JPanel and then I would like to add PlotData (DrawProfile and PlotData classes implement paintComponent method). DrawProfile class will draw some rectangular shapes which are filled by different colors. After that, PlotData which is just like a normal plot will sit on the top of DrawProfile(a rectangle with different colors). I want my PlotData to set its background according to DrawProfile different colorful shapes. It could be written a follows:

profile.setLayout(new OverlayLayout(profile));
profile.setPreferredSize(new Dimension(400,650));
profile.add(new DrawProfile());
profile.add(new PlotData());

Note that I have used profile.setOpaque(), but it did not help me. I used AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f) for DrawProfile. It works, but the problem is that the scatter plot colors are affected by DrawProfile objects, and the colors are not sharp. You can see my efforts here. At the end I will add my main JPanel (profile) to the JFrame.

EDIT: Regarding a runnable code, that would be hard. Because, the code might be intractable. To make my question clearer:

In DrawProfile, I extend the class by JComponent. I also implemeted paintComponent() method, where there is a draw(Graphics g) method inside the paintComponent() in order to draw multiple rectangulars with different colors. I set AlphaComposite to 0.5f inside the paintComponent() method.

In PlotData class, I used JFreechart (XYplot), and this class extends JPanel. Within this class, there is a paintComponent() method which does plotting (I don't do any strange things here). Inside paintComponent(), I don't touch AlphaComposite (In fact, it is 1.0f).

By doind above way, I was able to get my job done. but as you see in the link that I provided, PlotData objects do not have sharp colors.

NOTE that PlotData extends 'JPanel', while DrawProfile extends JComponents.

Please correct me if I am wrong. It seems that when we add JComponents objects to a JPanel, the first added JComponent object will be always stay on the top of the later added objects. For instance, in my provided example, I first added DrawProfile, so this class is sit on the top of my PlotData that I added it as my second JComponent object.


Solution

  • Actually I found the solution. JFreechart creates default background to draw a chart. What I did in the paintComponent() of PlotData, I set chart.setBackgroundPaint(null); ; and it solved my problem.