uday gowda
uday gowda

Reputation: 619

How to add components to JDialog

   d1=new JDialog();
   d1.setSize(200, 100);
   t1=new JTextField();
   t1.setBounds(10,10,40,20);
   d1.add(t1);

I want to add components in JDialog such as TextField, Button...

Upvotes: 6

Views: 35124

Answers (4)

padman
padman

Reputation: 501

1) first create a Jpanel

JPanel pan=new JPanel();
pan.setLayout(new FlowLayout());

2) add the components to that JPanel

pan.add(new JLabel("label"));
pan.add(new JButton("button"));

3) create JDialog

JDialog jd=new JDialog();

4) add the JPanel to JDialog

jd.add(pan);

Upvotes: 12

Guillaume Polet
Guillaume Polet

Reputation: 47607

I am not sure of how you really want your components to be laid out but the following snippet should achieve what I am guessing you are trying to do with your current code. Try to work as much as possible with LayoutManager's, Layout constraints, preferred/maximum/minimum sizes and avoid using setLocation/setSize/setBounds.

import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test5 {

    protected static void initUI() {
        JDialog dialog = new JDialog();
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 0));
        JTextField textfield = new JTextField(8);
        textfield.setBounds(10, 10, 40, 20);
        panel.add(textfield);
        dialog.add(panel);
        dialog.setSize(200, 100);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                initUI();
            }
        });
    }

}

You should probably read about LayoutManager's. Take the time to go through it, understand how they work and the different ones that exists. You won't regret spending a few minutes on that.

Upvotes: 0

Vedant Agarwala
Vedant Agarwala

Reputation: 18819

You can add components to a JDialog just the way you add to a JFrame since JDialog is a java.awt.Container . You should use a a layout manager or set the layout to null if you want to set the sizes of the components you are adding.

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68887

You have to make sure you use no layout manager.

d1.setLayout(null);

By default, a BorderLayout is used. It is great to use layout manager, but the real good ones, that make your windows resizable etc, are hard to understand. Without layout manager, you can specify the bounds as you tried.

Upvotes: 0

Related Questions