javaswinglayoutpanelminimum-size

define container minimum size using java layouts


i am writing a stand alone app in java using a couple of JPanel with different layouts in order to arrange the user interface. now my problem is that when i take the upper side of the window (its a pannel in a border layout which is inside another panel which using border layout),im tring to add a class that extends panel is order to paint an icon on the top of my window (draw on the panel) . the problem is that the layout is cuting a part of the icon, or in other words, minimazing the panel to a certain size. i tried changing to flowlayout and others but is does the same... so i wanted to ask if an option which tells the layout that a container (panel or others) can not be set to a size lower then a given size exists? other suggestions will allso help but keep in mind that i am tring to add the icon with mininal change to the GUI.

thanks for reading this and helping moshe


Solution

  • Container can hold MinimumSize for JComponent, simple example,

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class CustomComponent extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        public CustomComponent() {
            setTitle("Custom Component Graphics2D");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public void display() {
            add(new CustomComponents());//
            pack();
            // enforces the minimum size of both frame and component
            setMinimumSize(getSize());
            setVisible(true);
        }
    
        public static void main(String[] args) {
            CustomComponent main = new CustomComponent();
            main.display();
        }
    }
    
    class CustomComponents extends JPanel {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        public Dimension getMinimumSize() {
            return new Dimension(100, 100);
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 300);
        }
    
        @Override
        public void paintComponent(Graphics g) {
            int margin = 10;
            Dimension dim = getSize();
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
        }
    }