Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

swing - Using Java pack() method

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 )
    {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run()
        {
         JavaGui mygui = new JavaGui();
   //       mygui.setSize(1154, 753);
            mygui.setVisible(true);
            mygui.pack();

Class 2:

public class JavaGui extends javax.swing.JFrame 
    {
    public JavaGui()
        {
        getContentPane().setLayout(null);
        ..
        getContentPane().add(panelLeft);
        ...
        getContentPane().add(panelRight);

I tried putting the pack method in everywhere, but it's not going to work with this way of adding gui elements. Any suggestions why? I also tried adding everything to a JFrame instead of the getContentPane(), but I can't make that work either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...