Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JPanel and setOpaque method  RSS feed

 
Aabha Varma
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have created two panels. And overridden the paint method.
some images are drawn on the main panel, and on top of it i am placing a glass panel, with set opaque as false.

I want to do some stuffs like glass painting..
where the background shouldnt change, but the one on the top should change.
But when i am doing a repaint() for the glasspanel objects, i am able to see the object moving in the glass panel, but the back ground remains blank..

I am attaching a rough work along with.
My intention is , to improve the performance, the one in the background remains as such but only the glasspanel repaint will be called..

Can anybody help me. or provide me with some good techniques to reach the goal.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;

public class GlassClass extends JFrame
{
private JPanel panelMain ;
private JPanel panelGlass;
private int valuex;
private int valuey;
public GlassClass()
{

this.setSize(300,300);
panelMain = new MainPanel();
panelGlass = new GlassPanel();
panelGlass.setOpaque(true);

panelMain.setLayout(new BorderLayout());
panelMain.add(panelGlass,BorderLayout.CENTER);

this.getContentPane().add(panelMain, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// if the method is commented, both the images on main panel and
// and glass panel are visibel
drawMethods();

this.setVisible(true);

}

private void drawMethods()
{
Thread A =new Thread()
{
public void run()
{
while(true)
{
try
{
this.sleep(50);
valuex = valuex+1;
valuey = valuey+1;
panelGlass.repaint();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
A.start();
}
public static void main(String[] args)
{
GlassClass gc = new GlassClass();
}

class MainPanel extends JPanel
{
public MainPanel()
{

}

public void paint(Graphics g)
{
super.paint(g);
this.setBackground(Color.WHITE);
g.setColor(Color.RED);
g.fillRect(10,10,30,30);
}
}


class GlassPanel extends JPanel
{
public GlassPanel()
{

}

public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.GREEN);
//g.setXORMode(Color.RED);
g.fillOval(valuex,valuey,10,10);
g.fillRect(40,40,10,10);
}
}
}
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The GlassPane is set for the JFrame and is considered part of the JRootPane (see JRootPane api for details). Your application seems to run okay with the changes marked by /***/.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!