Ashutosh K Singh
Ashutosh K Singh

Reputation: 295

How to create a frame with a 'title', without creating the instance of JFrame class explicitly?

I want to create a frame with a 'Title' , by inheriting the JFrame class, so that I don't need to create an instance of frame class explicitly. How to do it?

Following is my code:

import javax.swing.*;

public class FrameByInheritance extends JFrame{//inheriting JFrame  

    FrameByInheritance(String s){  
        JButton b=new JButton("Submit");//create button  
        b.setBounds(130,100,100, 40);  

        add(b);//adding button on frame  
        setSize(400,500);  
        setLayout(null);  
        setVisible(true); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    }

    public static void main(String[] args) {  
        new FrameByInheritance("Set me in frame Title bar");
        //How to set title without craeting instance of parent class - JFrame
    }
}

The above code generates a frame, but without any 'Title' in the title bar. To set a title I will have to create an instance of the JFrame class and pass the title as an argument to its constructor as follows:

JFrame f=new JFrame("Set me in frame Title bar");

But I don't want to explicitly create an instance of the JFrame class. So how to do it?

Upvotes: 1

Views: 420

Answers (3)

Juan Carlos Mendoza
Juan Carlos Mendoza

Reputation: 5794

Add this on the first line of your constructor:

super(s);

This will call the JFrame's constructor that takes a String argument as the title.

Upvotes: 2

LearningJava
LearningJava

Reputation: 1

Try writing

  super("title"); 

right at the top inside your constructor

Upvotes: 0

MrSandman
MrSandman

Reputation: 86

JFrame#.setTitle("foo");

Its as simple as that :)

Or in your case just setTitle("foo");

Upvotes: 0

Related Questions