Nothing in my JFrame appears

久未见 提交于 2019-11-28 13:33:11

问题


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

回答1:


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());



回答2:


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.




回答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);



回答4:


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.



来源:https://stackoverflow.com/questions/10790292/nothing-in-my-jframe-appears

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!