除非监视器是一定的大小,否则最大化JFrame?

时间:2014-03-01 19:17:42

标签: java swing

有没有办法将JFrame最大化到某个分辨率以下(最高可达1024x768),但如果显示器较大,是否将大小固定在该分辨率上?

我理解.setExtendedState()是如何工作的,但无论显示器大小如何,这只会最大化它。

2 个答案:

答案 0 :(得分:1)

Toolkit's getScreenSize()方法可让您获得屏幕尺寸。

Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
System.out.println(screenSize); 
// use this information in a getPreferredSize() override.

这可能是覆盖JFrame的情况。例如,

class MyFrame extends JFrame {
   public static final int MAX_WIDTH = 0x400;
   public static final int MAX_HEIGHT = 0x300;

   @Override
   public Dimension getPreferredSize() {
      Toolkit toolkit = Toolkit.getDefaultToolkit();
      Dimension screenSize = toolkit.getScreenSize();
      int maxWidth = Math.min(screenSize.width, MAX_WIDTH);
      int maxHeight = Math.min(screenSize.height, MAX_HEIGHT);

      return new Dimension(maxWidth, maxHeight);
   }
}

答案 1 :(得分:1)

您可以检查屏幕尺寸,然后做出相应的决定。

以下示例说明:

import java.awt.Dimension;
import java.awt.Toolkit;

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

public class MaximizedFrame
{
  private static final int MAX_WIDTH = 1024;
  private static final int MAX_HEIGHT = 768;

  public MaximizedFrame()
  {
    JFrame frame = new JFrame("Maximized Frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = screenSize;

    if (screenSize.width > MAX_WIDTH || screenSize.height > MAX_HEIGHT)
    {
      frameSize = new Dimension(MAX_WIDTH, MAX_HEIGHT);
    }

    frame.setPreferredSize(frameSize);
    frame.setMinimumSize(frameSize);
    frame.setMaximumSize(frameSize);

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

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