Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

what exactly does setVisible(true) do?? details plz..  RSS feed

 
Manoj Pandey
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am dynamically adding JLabel's to a JPanel which is added to a JFrame, now the labels are not visible until iI call setVisible method of the JFrame or the show method of the JFrame,. I am confused as the component is already visible when this is bieng done.
here's the code..

import javax.swing.border.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MyJP extends JPanel {
Border border1;
JLabel jlabel;
FlowLayout flowLayout1 = new FlowLayout();
JButton jButton1 = new JButton();
public MyJP() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
LabelsTry labelsTry1 = new LabelsTry();
}
private void jbInit() throws Exception {

border1 = BorderFactory.createMatteBorder(4,4,4,4,Color.red);
jButton1.setBackground(Color.pink);
jButton1.setText("press to test");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
this.setBackground(Color.white);
this.setLayout(flowLayout1);
this.add(jButton1, null);
}
void jButton1_actionPerformed(ActionEvent e) {
jlabel=new JLabel(new ImageIcon("cfd.gif"));
//use any image
jlabel.setText("pressed the button yes man!! ");
add(jlabel);

repaint();

LabelsTry.jf.setVisible(true);
/*
if I comment out the above method call, the Jlabel's do not appear
*/
}
}

public class LabelsTry
{
static LabelsTry labelstry;
static JFrame jf;
LabelsTry(){
LabelsTry labelstry;
jf=new JFrame();
jf.setSize(300,300);
MyJP myjp=new MyJP();
myjp.setSize(300,300);
jf.getContentPane().add(myjp);
jf.show();
}
public static void main(String args[]){
labelstry = new LabelsTry();
}
}
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
show() and setVisible( true ) are basically the same command. I think that it is a side effect of what they do that is making the call in your program work... a call to validate() or repaint() may work just as well. ( I would bet on validate(), especially since you are dynamically adding new components... ) I believe both of these methods are called inside the show() and setVisible() methods.

-Nate
 
Manoj Pandey
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks Nate for the expalnation, repaint() does not wrk , Ithink validate would
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!