Widgets behaving strangely when using “setlayout(null)”

六眼飞鱼酱① 提交于 2019-11-29 18:07:07
  1. Avoid setLayout (null), unless you have a very good reason for it. You can learn about layout managers here: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

  2. If you still want to use a null layout, you have to set the width and height of the component, not just its x and y position (see the setSize method).

From the link mentioned above:

Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales.

I'd recommend using the setBounds method instead of the setLocation

    JTextField tf = new JTextField(10);
    Dimension d = tf.getPreferredSize();
    tf.setBounds(x, y, d.width, d.height);

Of course, if you're using a null Layout manager, you also need to take care of your preferredSize. Here's an example that incorporates all the major aspects:

import java.awt.*;
import javax.swing.*;

public class TestProject extends JPanel{

    public TestProject(){
        super(null);

        JTextField tf = new JTextField(10);
        add(tf);

        Dimension d = tf.getPreferredSize();        
        tf.setBounds(10, 20, d.width, d.height);

    }

    @Override
    public Dimension getPreferredSize(){
        //Hard coded preferred size - but you'd probably want 
        //to calculate it based on the panel's content 
        return new Dimension(500, 300);
    }

    public static void main(String args[])
    {


        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                frame.setContentPane(new TestProject());    
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!