0

I am practicing using GUIs. I have been following a set of instructions however when I try to run the program only an empty frame appears. No information can be seen inside the frame.

here is the code I have:

package practice528;

import java.util.Scanner;
import java.io.*;
import javax.swing.*;
import java.awt.*;

public class Practice528 
{
public static void main(String[] args) 
{
    JFrame frame = new JFrame("Rectangle Calculator");
    frame.setVisible(true);
    frame.setSize(400,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel lengthL, widthL, areaL, perimeterL;
    lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
    widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
    areaL = new JLabel("The area is ", SwingConstants.RIGHT);
    perimeterL = new JLabel("The perimeter is ", SwingConstants.RIGHT);

    frame.setLayout(new GridLayout(5,2));


    System.out.println();
} //end main
} //end class
Bart
  • 19,692
  • 7
  • 68
  • 77

4 Answers4

3

Simple: Don't call setVisible(true) on the JFrame before adding components to it. Call this only after the whole thing has been set up, at least initially.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
3

Add the components to the content pane :)

Here is a suggestion using the versatile MigLayout:

JPane panel = (JPanel) frame.getContentPane();
panel.setLayout(new MigLayout("fill, wrap 2", "[right][fill]"));

panel.add(lengthL);
panel.add(new JTextField());
panel.add(widthL);
panel.add(new JTextField());
panel.add(areaL);
panel.add(new JTextField());
panel.add(perimeterL);
panel.add(new JTextField());
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
  • +1 for mentioning miglayout. Miglayout really is a nifty time saver. download it here: http://www.miglayout.com/ and add it to the classpath, or use maven :) – Maarten Blokker May 28 '12 at 21:11
3

You should add the components tpo the JFrame by using the following code:

frame.getContentPane().add(lengthL);
frame.getContentPane().add(widthL);
frame.getContentPane().add(areaL);
frame.getContentPane().add(perimeterL);
Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
0

you need add Jlabels in frame like under given.

frame.add(lengthL);
frame.add(widthL);
frame.add(areaL);
frame.add(perimeterL);

this only add labels you created if you want another component then create and add it to frame.ex text field.

Tejas
  • 43
  • 1
  • 7