Some people have asked how to set the inner region of a JFrame to an exact size.
Usually the size wished is the dimensions passed to the setSize(int width, int height)
method, but the inner area of the JFrame is always smaller than the outer size of the
JFrame because a JFrame has Insets. For instance a frame with the dimensions
width = 500, height = 500 would have an inner region with the size
width = 492, height = 473 after the insets are subtracted. The following
code illustrates this.
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Client{
public static void main(String[] args){
DrawArea da = new DrawArea();
JFrame jf = new JFrame();
jf.addComponentListener(da);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(500,400);
jf.getContentPane().add(da);
jf.setVisible(true);
}
}
class DrawArea extends Canvas implements ComponentListener{
private String jfsize;
private JFrame jf;
private Insets insets;
private int insetwidth;
private int insetheight;
public void componentResized(ComponentEvent evt){
jf = (JFrame) evt.getSource();
jfsize = jf.getSize().toString();
insets = jf.getInsets();
insetwidth = insets.left + insets.right;
insetheight = insets.top + insets.bottom;
}
public void componentHidden(ComponentEvent e){}
public void componentMoved(ComponentEvent e){}
public void componentShown(ComponentEvent e){}
public void paint(Graphics g){
g.drawString("JFrame Size: " + jfsize, 0 ,50);
g.drawString("Inner Draw Region: " + g.getClipBounds().toString(),0,80);
g.drawString("Inset Width: " + insetwidth,0,110);
g.drawString("Inset Height: " + insetheight,0,140);
}
}
So what do we do to create a JFrame with an inner-region of an exact size? How big
would we have to make a JFrame in order to get an inner region the size w=397 h=256?
Simply set the size of your JFrame to the desired inner size,then get the left and right insets
add them togther next get the top and bottom insets and do the same.
Then add the total inset width and height values to the your JFrames orginal width and height.
ie.. jf.setSize((int)size.getWidth() + insetwidth,(int)size.getHeight() + insetheight);
Code:
import java.awt.*;
import javax.swing.*;
public class Client{
public static void main(String[] args){
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(397,256);
jf.setVisible(true);
Dimension size = jf.getSize();
System.out.println(size);
Insets insets = jf.getInsets();
int insetwidth = insets.left + insets.right;
int insetheight = insets.top + insets.bottom;
System.out.println("Insets left and right = " + insetwidth);
System.out.println("Insets top and bottom = " + insetheight);
jf.setSize((int)size.getWidth() + insetwidth,(int)size.getHeight() + insetheight);
System.out.println(jf.getSize());
}
}