Using Java pack() method

后端 未结 3 1273
误落风尘
误落风尘 2020-12-17 07:29

I can\'t make the pack() method work. I tried several things. My code looks like this at the moment:

Class 1:

public static void main( String[] args          


        
3条回答
  •  一个人的身影
    2020-12-17 08:10

    1. Don't use null layouts together with pack(). The pack method tells the layout managers and components to size themselves optimally, and if you instead use null layouts, then the gui risks shrinking to a minimal size, since there is no layout to hold it together.
    2. Don't use null layouts at all for the most part. Using these risk your creating rigid GUI's that are almost impossible to extend, improve, debug.
    3. Don't use setSize(...) and pack(). The layouts mostly respect the preferred sizes of components, not their sizes.

    Instead:

    1. Use a pleasing and sensible combination of nested JPanels, each using its own layout manager.
    2. Let the components and the layout managers size themselves.
    3. Then pack should help.
    4. The general order that I do is to add all components to the GUI, then call pack(), then setLocationByPlatform(true) (I think), then setVisible(true).

    For better help, please check out the Swing Layout Manager Tutorials.

    Here are a couple examples to other questions on this site that use various layout managers:

    • A combination of BorderLayout and GridLayout to create a calculator
    • BorderLayout and BoxLayout Combination for labels and JTextFields
    • Using GridBagLayout to create flexible label/textfield grid

提交回复
热议问题