zeawoas
zeawoas

Reputation: 466

how to do auto-resizing drawings in JPanel?

what's the easiest way to have a drawing in a JPanel that resizes whenever the user resizes the JFrame?

I know that I can auto resize the panel with a BorderLayout but the drawings are not resized in this case. I am new to java and GUI programming and there are probably numerous solutions.

please give me a hint into the right direction to make e.g. the rectangle in

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

public class DrawRect extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        g.drawRect(20, 20, 100, 100);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        DrawRect panel = new DrawRect();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(200, 200));
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

auto-resizing whenever the frame is resized.

Upvotes: 1

Views: 504

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168845

Provide positions and sizes as a proportion of the width and height of the panel. Whenever the panel is resized, the rendering engine will schedule a call to the paintComponent() method and the rectangle will be drawn proportionally. E.G.

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

public class DrawRect extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.drawRect(w/10, h/10, w/2, h/2);
    }

    /* A custom component should give the layout manager hints as to
    its preferred size. */
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200,200);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        DrawRect panel = new DrawRect();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 3

frame.getContentPane().setLayout(new BorderLayout());

Insert the line before you add the component to the GUI.

You should study layoutmanagers, since it is a unique concept in Java.

Upvotes: 0

Related Questions