Reputation: 419
I can't understand why in the following code only the button is being displayed , and why aren't label and textfield displayed.
import javax.swing.*;
import java.awt.*;
class Invent extends JFrame
{
public Invent(){
JFrame c=new JFrame("trying");
JLabel label1;
JTextField txtfld1;
JButton buttoncomp;
label1=new JLabel("Enter the path");
txtfld1=new JTextField();
buttoncomp=new JButton("Update");
c.add(label1);
c.add(txtfld1);
c.add(buttoncomp);
c. pack();
c.setVisible(true);
}
public static void main(String[] args)
{
new Invent();
}
}
Kindly help ...
Upvotes: 0
Views: 155
Reputation: 386
It works incorrect(for you but java does what you say :) )
cause you add (these)three components to JFrame in row(the next remove the last)
you must work as follows:
label1.add(txtfld1);
label1.add(buttoncomp);
c.add(label1);
c.pack();
c.setVisible(true);
And something other...
Let me know if that works for you...
Upvotes: -1
Reputation: 42174
The default layout of a JFrame's content pane is BorderLayout. You're adding all of your components to the BorderLayout.CENTER location (by calling the single-argument add() function), which means that only the last component is added.
Either use a different layout manager, or add the components to different locations in the BorderLayout.
More info about BorderLayout can be found here.
Btw, your title has nothing to do with your actual question: the difference between a JFrame and a content pane is that a JFrame contains a content pane. The JFrame class passes calls like setLayout() and add() to its content pane.
Upvotes: 5