启动应用程序时设置JFrame的最大大小 [英] Setting the Maximum size of a JFrame while launching the application
问题描述
我想在启动应用程序时设置JFrame的最大大小. 问题是,如果屏幕分辨率更高,则我的帧会越来越大,但那时它不应该超过定义的最大范围,但是在低分辨率下,同样的情况也能很好地工作.
I want to set the Maximum size of the JFrame while launching the application. Problem is, if the screen resolution is more my frame is getting bigger , but at that time it should not cross the max range defined, but same case works fine with low resolution.
就像我希望我的框架最大为(500,500)一样,所以我写了这段代码:
Like I want my frame to be of Maximum of (500,500) , so I wrote this piece of code:
JFrame frame = new JFrame("FRAME TRANSPARENT");
frame.setSize((int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth()-50), (int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight()-150));
frame.setMaximizedBounds(new Rectangle(0,0 , 500, 500));
frame.setVisible(true);
即使我设置了Bound,JFrame也在考虑setSize方法,而且似乎忽略了setMaximizedBounds方法. 我已经尝试过使用setMaximumized方法,但是得到了相同的输出.
Even I set the Bound, the JFrame is considering setSize method and it seems to be that it is neglecting the setMaximizedBounds method. I already tried with setMaximumized method but got the same output.
推荐答案
我尝试了一下,您说对了,以至于setMaximumSize()
无法正常工作.我对限制大小的要求通常由setResizable(false)
固定,尽管我看到您对最小和最大大小的特定查询有所不同
I tried it and you're so right that setMaximumSize()
doesn't work.. all these years couldn't get to know that!!! Mostly my requirements of limiting size is fixed by setResizable(false)
, although I see you have specific query of minimum and maximum sizes to be different
尽管如此,但仍为您解决了一个问题:
Worked on a solution for you though:
public class MaxSizeUI
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MaxSizeUI().makeUI();
}
});
}
public void makeUI() {
final JFrame frame = new JFrame("Sample Fram") {
@Override
public void paint(Graphics g) {
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize) {
Point p = getLocation();
setVisible(false);
setSize(d);
setLocation(p);
setVisible(true);
}
super.paint(g);
}
};
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setMaximumSize(new Dimension(400, 200));
frame.setMinimumSize(new Dimension(200, 100));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
这篇关于启动应用程序时设置JFrame的最大大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!