JFrame不符合JPanel的setMinimunSize()

时间:2015-04-26 07:42:08

标签: java swing jframe jpanel

我希望JPanel的{​​{1}}限制setMinimumSize()的大小调整,但事实并非如此。

以下是我的示例代码:

JFrame

如果您将import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSplitPane; public class AutoResize{ public static void main(String[] args) { JPanel leftPanel = new JPanel(); JPanel rightPanel = new JPanel(); leftPanel.setBackground(Color.RED); rightPanel.setBackground(Color.BLUE); leftPanel.setSize(500,400); rightPanel.setSize(500,400); Dimension d = new Dimension(450,300); leftPanel.setMinimumSize(d); rightPanel.setMinimumSize(d); JSplitPane split; split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel); split.setDividerLocation(400); JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(split, BorderLayout.CENTER); frame.setSize(1000, 800); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } 调整为非常小的尺寸,则会产生以下结果: weird behaviour

我想要的是JFrame无法调整为比JFrame s'最小尺寸更小的区域。反正有没有实现这个?

1 个答案:

答案 0 :(得分:0)

我只需要添加frame.setMinimumSize();,我感到愚蠢。

感谢@Andrew Thompson @MadProgrammer和@ user1803551

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class AutoResize{

    private final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    private final double w = screenSize.getWidth();
    private final double h = screenSize.getHeight();
    private final Dimension d = new Dimension((int) w/3,(int) h/3);

    public void run() {
        JPanel leftPanel = new JPanel();
        JPanel rightPanel = new JPanel();
        leftPanel.setBackground(Color.RED);
        rightPanel.setBackground(Color.BLUE);
        //leftPanel.setSize(500,400);
        //rightPanel.setSize(500,400);
        leftPanel.setMinimumSize(d);
        rightPanel.setMinimumSize(d);

        JSplitPane split;
        split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        split.setDividerLocation(400);

        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(split, BorderLayout.CENTER);

        frame.setSize((int) w,(int) h);
        //frame.pack();
        frame.setMinimumSize(new Dimension((int) w/3*2,(int) h/3*2));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        AutoResize test = new AutoResize();
        test.run();
    }
}