Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a JFrame a certain size, not including the border?

I have a JFrame that I've set to a certain size, using setBounds. However, that makes the window, including the borders, that size (which in hindsight makes complete sense). But what I want is for the size of the window it be, say, 800x600 plus the borders. This is important because I'm drawing to a Graphics object from the BufferStategy from the JFrame, but I've been drawing underneath the title bar when using a y value of less than about 20. I imagine different OSs (or even different OS settings) can have different thickness borders, too. I thought the borders were just tacked on a window afterwards, but this doesn't seem to be the case.

So, how do I make the space inside the borders a certain size, regardless of the thickness of the borders? Also, to make my life easier, how do I make point 0, 0 be the top left corner of the viewable contents of the frame?

By the way, using setUndecorated presents it's own problems, so I'm not trying that at the moment.

like image 713
AlbeyAmakiir Avatar asked Dec 04 '25 09:12

AlbeyAmakiir


2 Answers

  1. Set a preferred size for the content pane.
  2. Pack the frame.
  3. Job done.

E.G.

Fixed Size Content

import java.awt.*;
import javax.swing.*;

class FixedSizeContent {
    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JFrame f = new JFrame("Fixed size content");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                Container c = f.getContentPane();
                c.setBackground(Color.YELLOW);
                // adjust to need.
                Dimension d = new Dimension(400,40);
                c.setPreferredSize(d);
                f.setResizable(false);
                f.pack();
                f.setVisible(true);
            }
        });
    }
}
like image 179
Andrew Thompson Avatar answered Dec 05 '25 22:12

Andrew Thompson


let the drawing component report the size of the graphic as its pref

 @Override
 public Dimension getPreferredSize() {
      return new Dimension(myDrawing.getWidth(), myDrawing.getHeight());  
 } 

then follow @Andrew's bullets 2 and 3

like image 22
kleopatra Avatar answered Dec 05 '25 22:12

kleopatra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!