How to add components to JDialog

2019-01-28 06:30发布

问题:

   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...

回答1:

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);


回答2:

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.



回答3:

Take a look of this example and tutorial ..
1. How to Make Dialogs
2. Dynamically Add Components to a JDialog
3. add components inside JDialog



回答4:

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.



回答5:

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.