首页 > 解决方案 > 为什么有时swing JPanel布局会自动调整到最小

问题描述

当我双击摇摆罐时,它显示正常。按钮,文本字段和标签按预期显示。 在此处输入图像描述 但经过一段时间后,JPanel 会自动调整为最小值,如下所示。我已经设置了框架 setResizable(false) 在此处输入图像描述 任何人都可以给出一些想法吗?

    public TestSwing() {
        super(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        log = new JTextArea(18, 45);
        log.setMargin(new Insets(5, 5, 5, 5));
        log.setEditable(true);
        logScrollPane = new JScrollPane(log);
        DefaultCaret caret = (DefaultCaret) log.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        btn_source = new JButton("open");
        btn_dest = new JButton("open");
        lbl_sourceFile = new JLabel("Source Excel File:");
        lbl_destFile = new JLabel("Destination XML Folder:");
        txt_source = new JTextField(45);
        txt_dest = new JTextField(45);
        btn_convert = new JButton("Convert");

        c.fill = GridBagConstraints.VERTICAL;
        c.insets = new Insets(0, 0, 0, 0);
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 1;
        add(lbl_sourceFile, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 0;
        c.gridwidth = 1;
        add(txt_source, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 0;
        c.insets = new Insets(0, 10, 2, 0);
        c.gridwidth = 1;
        add(btn_source, c);
    }

    public void actionPerformed(ActionEvent e) {}

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TestLink Converter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TestSwing());
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

标签: javaswingjpanel

解决方案


frame.add(new TLSwing());

我们不知道“TLSing()”类是什么,但我猜它是一个使用 GridBagLayout 的面板。当没有足够的空间以首选大小显示组件时,组件将以最小大小显示,因此您的文本组件会缩小。

我已经设置了框架 setResizable(false)

您应该在 pack() 框架之前设置调整大小状态。

frame.setResizable(false);
frame.pack();
frame.setVisible(true);
//frame.setResizable(false);

推荐阅读