1

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    1) Prefer [composition over inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance). For a common frame type, use a factory method. 2) `setLayout(null);` Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Nov 23 '17 at 18:45
  • Thanks for introducing me to a new concept, it is very helpful. – Ashutosh K Singh Nov 23 '17 at 19:05

3 Answers3

2

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.

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
0

JFrame#.setTitle("foo");

Its as simple as that :)

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

MrSandman
  • 86
  • 1
  • 8
0

Try writing

  super("title"); 

right at the top inside your constructor