Java window contents resize, but not beyond a minimum size

前端 未结 2 476
说谎
说谎 2020-12-21 11:35

I have a Java apps I\'ve written using NetBeans (yes, I\'ve read plenty of complaints here about NetBeans). When I resize the window, the contents resize with the window, u

相关标签:
2条回答
  • 2020-12-21 12:24

    yes and very simple solution just override and return getMinimumSize()

    for example

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class CustomComponent extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        public CustomComponent() {
            setTitle("Custom Component Test");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public void display() {
            add(new CustomComponents(), BorderLayout.NORTH);
            add(new CustomComponents(), BorderLayout.CENTER);
            add(new CustomComponents(), BorderLayout.SOUTH);
            add(new CustomComponents(), BorderLayout.EAST);
            pack();
            // enforces the minimum size of both frame and component
            setMinimumSize(getMinimumSize());
            setPreferredSize(getPreferredSize());
            setVisible(true);
        }
    
        public static void main(String[] args) {
            CustomComponent main = new CustomComponent();
            main.display();
        }
    }
    
    class CustomComponents extends JLabel {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        public Dimension getMinimumSize() {
            return new Dimension(200, 100);
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }
    
        @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);
        }
    }
    
    0 讨论(0)
  • 2020-12-21 12:30

    Can we see some example code? I believe that its not the window but the content inside the window that's not resizing beyond a certain point.

    0 讨论(0)
提交回复
热议问题