0

I am just new to Java. When I run the program below I get nothing - no JLabel is added to the window

  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import java.awt.FlowLayout;

  public class MainProgram{

  public static void main(String[] args) {
    JFrame frame = new JFrame("This is the title of the window");//adding the JFrame or window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//so it really and literally close when we 
    //hit the close button on the window
    frame.setVisible(true);//setting the visibility
    //adding the label
    JLabel label_1 = new JLabel("this is a JLabel");
    //adding the label to the window
    label_1.setToolTipText("This is the tool tip");
    add(label_1);
}
}

Any suggestions?

Muneeb Ejaz
  • 696
  • 6
  • 11
  • See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. – Andrew Thompson Jun 02 '16 at 13:20
  • 2
    `frame.setVisible(true);//setting the visibility` This should be done after all the components have been added. It is typically the last line of code in the `main`.. – Andrew Thompson Jun 02 '16 at 13:22
  • You're adding the label to the current program (which I assume extends a JFrame or JPanel), then you're creating another JFrame within your main method and displaying that instead of the current one. – ManoDestra Jun 02 '16 at 13:57

3 Answers3

0

First of all, this is wrong code.

public class MainProgram extends { // extends What?

But, what you are doing wrong is that you are adding the JLabel to whatever you extend, and not to your frame. So, change this line:

add(label_1);

to

frame.add(label_1);
dryairship
  • 6,022
  • 4
  • 28
  • 54
  • hi Sorry when i copied code to post on stackoverflow i accidently put extends .. and it does not compile if do frame.add(label_1) – Muneeb Ejaz Jun 02 '16 at 17:31
0

You need add your component to your frame frame.add(label_1);and set the dimension of your frame

xy1m
  • 61
  • 3
0

just add this line

frame.pack(); 

try to set a dimension to the jlabel and the frame itself; when using add(Component) don't to forget frame before it, use it as following : frame.add(yourLabel);

The Appsolit
  • 89
  • 10
  • Thanks it worked ... How come this worked can you explain it? Thanks again. – Muneeb Ejaz Jun 03 '16 at 16:47
  • i'm refering to this post : The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size. see this http://stackoverflow.com/a/22982334/2228261 – The Appsolit Jun 03 '16 at 16:52