简体   繁体   中英

How to auto extend the height of frame in java swing

我创建了一个具有500,500尺寸的小框架,在我的框架中还添加了面板,我还动态添加了标签和文本框,我在面板中添加了10个标签,显示正确,但是我将添加上面的另外5个标签和文本框添加标签意味着5个标签和文本框被隐藏之后,因此如何自动扩展框架高度

Calling the .pack() method should do the trick:

public void pack()

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method. If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.

there are a few important rulles and required knowledge how concrete LayoutManager works with min, max and PreferredSize came from its childs

  1. I'd strongly suggest to add (re)validate() and repaint() for already visible Container

  2. use JScrollPane as first JComponent added to the JFrame / JDialog / JWindow and with to determine maximum size for JFrame (best could be from display resolution), don't use pack() in the case that maximum size is exceeded, otherwise containers bounds could be out of the screens

code example, have to add rules in point 2nd.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class AddComponentsAtRuntime {

    private JFrame f;
    private Container panel;
    private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;

    public AddComponentsAtRuntime() {
        JButton b = new JButton();
        b.setBackground(Color.red);
        b.setBorder(new LineBorder(Color.black, 2));
        b.setPreferredSize(new Dimension(600, 10));
        panel = new Container();
        panel.setLayout(new GridLayout(0, 1));
        panel.add(b);
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(panel, "Center");
        f.add(getCheckBoxPanel(), "South");
        f.setLocation(200, 200);
        f.pack();
        f.setVisible(true);
    }

    private JPanel getCheckBoxPanel() {
        checkValidate = new JCheckBox("validate");
        checkValidate.setSelected(false);
        checkReValidate = new JCheckBox("revalidate");
        checkReValidate.setSelected(false);
        checkRepaint = new JCheckBox("repaint");
        checkRepaint.setSelected(false);
        checkPack = new JCheckBox("pack");
        checkPack.setSelected(false);
        JButton addComp = new JButton("Add New One");
        addComp.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton b = new JButton();
                b.setBackground(Color.red);
                b.setBorder(new LineBorder(Color.black, 2));
                b.setPreferredSize(new Dimension(600, 10));
                panel.add(b);
                makeChange();
                System.out.println(" Components Count after Adds :" + panel.getComponentCount());
            }
        });
        JButton removeComp = new JButton("Remove One");
        removeComp.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int count = panel.getComponentCount();
                if (count > 0) {
                    panel.remove(0);
                }
                makeChange();
                System.out.println(" Components Count after Removes :" + panel.getComponentCount());
            }
        });
        JPanel panel2 = new JPanel();
        panel2.add(checkValidate);
        panel2.add(checkReValidate);
        panel2.add(checkRepaint);
        panel2.add(checkPack);
        panel2.add(addComp);
        panel2.add(removeComp);
        return panel2;
    }

    private void makeChange() {
        if (checkValidate.isSelected()) {
            panel.validate();
        }
        if (checkReValidate.isSelected()) {
            panel.revalidate();
        }
        if (checkRepaint.isSelected()) {
            panel.repaint();
        }
        if (checkPack.isSelected()) {
            f.pack();
        }
    }

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

            @Override
            public void run() {
                AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
            }
        });
    }
}

There's no boolean which you can set to true in order to make the frame grow automatically.

You probably want to do getPreferredSize() of the content panel each time you add something, and do frame.setSize(...) to accommodate for the new components.

Here's a demo

public class FrameTestBase {

    public static void main(String args[]) {
        final JFrame t = new JFrame();

        t.getContentPane().setLayout(new GridLayout(-1, 1));

        t.add(new JButton(new AbstractAction("Add label") {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                t.getContentPane().add(new JLabel("hello"));

                // Auto-adjust height.
                Dimension dim = t.getContentPane().getPreferredSize();
                dim.width = 500;
                t.setSize(dim);
            }
        }));

        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.setSize(500, 500);
        t.setVisible(true);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM