Java Swing: a component that resizes but does not affect the layout

I will try to explain my problem as simple as possible, but this is a complex topic, and people who have not encountered the problem will probably not know what I'm talking about.

I want to use BorderLayout using the West, East, North, South, etc. components, which are my “normal” components (JLabels, JButtons, etc.), then I want to so that the central component is an “image”: pixels). For this, I use BufferedImage and use setIcon in JLabel, which is located inside the panel, which is part of the "center".

However, I want my image / pixels to be “fluid”: whenever the user changes the size of the application, I want to calculate the exact size of the JLabel (icon / text space is set to 0), and then create a new image (pixels that I manipulate directly in BufferedImage, but whatever) that has exactly this size.

Now it works . But only when I change the size of the main window ("window", as in "one of the windows of the operating system", making it larger.

This does not work when I reduce the main window.

The reason, after many tests, is obvious, because the size of my JLabel (in which I did setIcon (img) affects the calculation of the layout manager.

, : BorderLayout ( ), "" ?

+3
2

, , ...

"", , getVisibleRect .

ImageIcon BufferedImage, 20 ( ), , .

, , , , / .

, , "" , .

, , , , , .

+2

, , , JLabel ( setIcon (img ) .

JLabel , , CENTER , , 4 .

BufferedImage setIcon JLabel, , "".

, .

BorderLayout. JLabel . ComponentListener . , , , . , , JLabel,

SSCCE:

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

public class LabelTest2 extends JFrame
{
    public LabelTest2()
    {
        JLabel picture = new JLabel(new ImageIcon("???.jpg"));
        add(picture);
    }

    public static void main(String[] args)
    {
        LabelTest2 frame = new LabelTest2();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
+1

Source: https://habr.com/ru/post/1769465/


All Articles