0

我有一个JFrame包含一个JButtonJFrame出现时,用户将调整大小JFrame,然后单击JButton哪个会做:

System.out.print("actual size now = "+JFrame.getsize");

但尺寸不会导致JFrame屏幕上的实际尺寸。

我使用时尺寸仍然错误:

  • JFrame.getSize

  • JFrame.getPrefferedSize

  • JFrame.getMinimumSize

  • JFrame.getMaximumSize

  • JFrame.getBounds

  • JFrame.getHeight&getwidth

我应该怎么办?

非常感谢任何帮助

4

1 回答 1

2

您获得的大小是JFrames contentPane 的大小和Inset添加的 s 的大小。只需调用并从您可以通过s获得的宽度高度JFrame#getInsets()中减去它们。JFrameJFrame#getSize()

这是一个例子:

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public Test() {
        initComponents();
    }

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

    private void initComponents() {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public Dimension getPreferredSize() {//the frame should now return a width and height of 300
                return new Dimension(300, 300);
            }
        };

        JButton button = new JButton("Get JFrame real width and height");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {

                Dimension frameSize = frame.getSize();
                Insets insets = frame.getInsets();

                System.out.println("Frame size via getSize(): " + frameSize);
                System.out.println("Insets: " + insets);

                double width = frameSize.getWidth();
                double height = frameSize.getHeight();

                //calculate real width/height
                double realWidth = width - (insets.left + insets.right);
                double realHeight = height - (insets.top + insets.bottom);

                System.out.println("Width: " + realWidth + " Height: " + realHeight);
            }
        });

        panel.add(button);
        frame.add(panel);

        frame.pack();
        frame.setVisible(true);

    }
}

输出:

通过 getSize() 获得的帧大小:java.awt.Dimension[width=316,height=338]

插图:java.awt.Insets[top=30,left=8,bottom=8,right=8]

宽度:300.0 高度:300.0

于 2012-11-04T14:34:16.797 回答