Mandy
Mandy

Reputation: 1

JPanel getpreferredsize() returns 10 instead of size of JFrame minus borders

I am trying to get the size of a JPanel so that I can subsequently calculate the correct dimension of graphics I plan to add. Since I have set the size of the JFrame to be (300, 200), I was expecting the getpreferredsize() function to return something slightly smaller than (300, 200) (i.e. minus border). However, the function simply returned 10 for both height and width. Please help.

import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.io.*;
import java.awt.Dimension;

class Main {
  public static void main(String[] args) {
    Frame f = new Frame();
  }
}

class Frame extends JFrame {
  
  public Frame() {
    setSize(300, 200);
    setLocationRelativeTo(null);
    setTitle("Test Panel Size");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    setVisible(true);  

    setLayout(new BorderLayout());
    add(drawPanel, BorderLayout.CENTER);
    pack();
    drawPanel.printPanelSize();
  }

  private Panel drawPanel = new Panel();
}

class Panel extends JPanel {

  public void printPanelSize() {
    Dimension size = getPreferredSize();
    int w = size.width;
    int h = size.height;
    System.out.println("h = " + h + " w = " + w);
  }

} 

Upvotes: 0

Views: 187

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Replace

setSize(300, 200);

with

setPreferredSize(new Dimension(300, 200));

and replace

 Dimension size = getPreferredSize();

with

Dimension size = getSize();

Upvotes: 1

Related Questions