Pages

How to know when a component has been made invisible or visible ???


In this example, we use button as component.

*************************************************************************
COMPLETE SOURCE CODE FOR : HowToKnowWhenComponentVisible.java
*************************************************************************


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import java.awt.event.ComponentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.awt.FlowLayout;

public class HowToKnowWhenComponentVisible
{
JFrame a=new JFrame("CLICK HERE");
JFrame b=new JFrame("FRAME TO STORE JBUTTON NAME'S MONSTER");

JButton c=new JButton("VISIBLE");
JButton e=new JButton("INVISIBLE");
JButton d=new JButton("MONSTER");

public HowToKnowWhenComponentVisible()
{
ComponentListener cl=new ComponentAdapter()
{
public void componentHidden(ComponentEvent evt)
{
JOptionPane.showMessageDialog(null,"MONSTER IS INVISIBLE");
}

public void componentShown(ComponentEvent evt)
{
JOptionPane.showMessageDialog(null,"MONSTER IS VISIBLE");
}
};

d.addComponentListener(cl);
b.add(d);

ActionListener al=new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==e)
{
d.show(false);
b.repaint();
}

if(evt.getSource()==c)
{
d.show(true);
b.repaint();
}
}
};

c.addActionListener(al);
e.addActionListener(al);
a.setLayout(new FlowLayout());
a.add(c);
a.add(e);

a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setSize(400,100);
a.setVisible(true);

b.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
b.setSize(400,100);
b.setLocation(400,400);
b.setVisible(true);
}

public static void main(String[]args)
{
HowToKnowWhenComponentVisible myObject=new HowToKnowWhenComponentVisible();
}
}


*************************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************************
Related Posts Plugin for WordPress, Blogger...