问题
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