Neeraj Yadav
Neeraj Yadav

Reputation: 422

Unable to set size of components correclty

I made a simple swing program to display Text Area and a button below it, but even after using setBounds(), button is getting displayed over full Frame. Here is my code-

import javax.swing.*;

class Exp2
{
  public static void main(String... s)
  {
    JFrame jf=new JFrame("Exec");
    JTextArea jtv=new JTextArea("Hello World");
    jtv.setBounds(5,5,100,60);
    JButton jb=new JButton("click");
    jb.setBounds(40,160,100,60);
    jf.add(jtv);
    jf.add(jb);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(500,500);
    jf.setResizable(false);
    jf.setVisible(true);
  }
}

After Execution of code

Upvotes: 1

Views: 27

Answers (1)

camickr
camickr

Reputation: 324088

Don't use setBounds(). Swing was designed to be used with layout managers.

The default layout manager for a frame is a BorderLayout. So you can't just add the button directly to the frame.

Instead your logic should be something like:

JButton button = new JButton(...);
JPanel wrapper = new JPanel();
wrapper.add(button);
frame.add(wrapper, BorderLayout.PAGE_START);

The default layout for a JPanel is a FlowLayout which will display the button at its preferred size.

Read the section from the Swing tutorial on Layout Manager for more information about the BorderLayout and FlowLayout.

Upvotes: 1

Related Questions