Java setBounds()方法(JFrame)

时间:2015-05-11 14:19:05

标签: java swing jframe dimension setbounds

您好我使用setBounds方法打开一个特定大小的窗口。但是我在参数中传递的大小是窗口的大小,包括框架的条形。如何仅为内容设置尺寸?

1 个答案:

答案 0 :(得分:1)

有两种方法可以解决这个问题:

  • 在设置框架边界时考虑框架的边框
  • 覆盖getPreferredSize()内容窗格的JFrame,然后在框架上调用pack()

以下是两种技术的演示:

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    protected void initUI() {
        JFrame frame = new JFrame("Insets technique");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        Insets i = frame.getInsets();
        System.out.println(i);
        Rectangle bounds = new Rectangle(50, 100, 400, 500);
        bounds.width += i.right + i.left;
        bounds.height += i.bottom + i.top;
        frame.setBounds(bounds);
    }

    protected void initUI2() {
        JFrame frame = new JFrame("Preferred size technique");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 500);
            }
        });
        frame.pack();
        frame.setLocation(50, 100);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test test = new Test();
                test.initUI();
                test.initUI2();
            }
        });
    }
}