If you don't know what "AdjustWidowRect" does, here's a description from MSDN:
Calculates the required size of the window rectangle, based on the desired client-rectangle size.
More clearly:
In swing, when you set the size of a JFrame, that includes the border. That means that if you set the size of the JFrame to 640 by 480, that will not be the client size, since the size you entered counts the size of the frames' border.
I want to have a rectangle, and be able to adjust it so when the JFrame's size is set to that rectangle, the client size of the JFrame is what the rectangle was before adjustment.
You have to compute the insets of the JFrame and add them to the desired client size, to set the size of the JFrame.
Insets insets = getInsets();
AFAIU the accepted answer does not account for menu bars or other components in the mix. This does, by overriding the preferred size of the component, and packing the frame.
I'm drawing graphics to the JFrame and I need it to be a precise size.
Don't paint to a top level container such as JFrame or JWindow. Instead render to a JPanel or BufferedImage and add it to the TLC.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SizedGUI {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(2,3,2,3));
gui.add(new FixedSizeComponent());
gui.setBackground(Color.RED);
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// tweak to ensure the GUI never gets too small
f.setMinimumSize(f.getSize());
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class FixedSizeComponent extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(400,100);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
g.setColor(Color.BLACK);
g.drawString(w + "x" + h, w/2, h/2);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With