简体   繁体   中英

adding Jlabel to a a panel from an extended class

I have a default window and its constructor and know what I want all my windows to setup like. Then I want to customize the rest of the windows with their respective interfaces.

import javax.swing.*;
import java.awt.*;

public class Default_window extends JFrame {

    protected BorderLayout layout = new BorderLayout();

    public Default_window(){
        setTitle("My Program");
        setLayout(layout);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Dimension Window_size = new Dimension(500,500);

        JPanel mypanel= new JPanel();

        add(mypanel, BorderLayout.CENTER);

        getContentPane();
        setResizable(false);
        setSize(Window_size);
        setVisible(true);

    }

}

this is the custom screen I am trying to create:

import javax.swing.*;


public class Login_screen extends Default_window{
    JLabel user_name = new JLabel("Username: ");

    public Login_screen(){
    // insert way to add Jlabels to the panel here. 

    }


}

But I can't just say add(user_name). It doesnt know where to put it. Any help is gladly appreciated. I am arecent college grad and no one around me knows anything about programming. #forever_alone

Default_window is extending JFrame , which is a top level container. You have to add your components to your JPanel which you named mypanel .

Try to create a 3rd class that extends JPanel , for example Default_panel and add your components there. Let Login_screen extend Default_panel , and then you will be able to call add(...) .

Inheritance in combination with creating a rather complex panel can be very difficult, especially if you want great flexibility (putting plugin components anywhere between the default components). I would therefore suggest to create some GUI builder class, which is responsible for collecting all component constraints, and when every component has been "registered", it can create the JPanel with a LayoutManager of your choice.

If you can avoid a pluggable GUI, avoid it.

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