Arc
Arc

Reputation: 449

Java force panel certain size

When I add a JPanel, whose size should be (300, 300), to my main JFrame, the entire JFrame is (300, 300), which should not be. The JPanel itself should be (300, 300).

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Tester extends JFrame {

    public Tester() {
        this.getContentPane().add(new Window());
        this.pack();

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
    }

    private void formMouseClicked(java.awt.event.MouseEvent evt) {                                  
        System.out.println("x: " + evt.getX() + ", y: " + evt.getY());
    }  

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tester().setVisible(true);
            }
        });
    }

    public class Window extends JPanel {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }
    }
}

Upvotes: 0

Views: 604

Answers (2)

Jalal Kiswani
Jalal Kiswani

Reputation: 755

The default layout for JFrame is BorderLayout , and when you add component without specifying the region, it will go by default to the center region, and the center region doesn't respect the preferred size of its component.

Regarding the the size of the frame, the pack method calculate it based on the internal components preferred sizes.

Upvotes: 1

camickr
camickr

Reputation: 324088

the entire JFrame is (300, 300), which should not be.

Why do you say this? If you click at the bottom right you will see values greater than 300.

Maybe what you want is:

    //this.getContentPane().add(new Window());
    JPanel panel = new Window();
    this.getContentPane().add(panel);
    this.pack();
    //addMouseListener(new java.awt.event.MouseAdapter() {
    panel.addMouseListener(new java.awt.event.MouseAdapter() {

Now all the mouse points will be relative to the panel.

Upvotes: 1

Related Questions