简体   繁体   中英

Java JFrame components

I'm trying to create a simple 500x500 applet with a button, 2-label, and textfield. The applet opens up but it is just blank no components are displaying nor will the color change. Not sure what is happening or what I'm missing exactly.

import java.applet.*;
import java.awt.Color;

import javax.swing.*;

public class Greeting {
private JFrame frame;
private JPanel panel;
private JLabel label1;
private JTextField textbox1;
private JButton button1;
private JLabel label2;

public Greeting(){
    gui();

}

    public void gui(){
        frame = new JFrame("Greeting");
        frame.setVisible(true);
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        panel = new JPanel();
        panel.setBackground(Color.YELLOW);

        label1 = new JLabel ("Please enter your name");
        textbox1 = new JTextField(20);
        button1 = new JButton ("Greet");

        panel.add(label1);
        panel.add(button1);
        panel.add(textbox1);

        frame.getContentPane().add(panel);
        frame.add(panel);
    }

    public static void main(String[] args) {
        new Greeting();

    }

}

If you are planning on displaying frame with all the components, then move the frame.setVisible(true) line to the end of the method:

public void gui() {
    ...
    frame.add(panel);
    frame.setVisible(true);
}

This allows for all the components to be added to the JFrame before it is displayed on the screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM