我在自定义JComponent中重写了getPreferredSize()和getMinimumSize()。虽然getPreferredSize()可以按预期工作,但由于我能够调整JFrame的大小,直到我的自定义组件消失,因此将忽略getMinimumSize()。为什么?如何避免呢?

这是一个完整的可运行程序,表明了我的观点。我究竟做错了什么?

Main.java

    package swing.minimumsize;

    import javax.swing.JFrame;

    @SuppressWarnings("serial")
    public class Main extends JFrame {

        public Main() {
            setTitle("Custom Component Test");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

        public void display() {
            add(new CustomComponent());
            pack();
            setVisible(true);
        }

        /**
        * @param args
        */
        public static void main(String[] args) {
            Main main = new Main();
            main.display();
        }

    }

CustomComponent.java
    package swing.minimumsize;

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;

    import javax.swing.JComponent;

    @SuppressWarnings("serial")
    public class CustomComponent extends JComponent {

        @Override
        public Dimension getMinimumSize() {
            return new Dimension(100, 100);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 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);
        }

    }

最佳答案

..getMinimumSize()会被忽略,因为我能够调整JFrame的大小,直到我的自定义组件消失为止。为什么?如何避免呢?

检查第一条评论。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main extends JFrame {

    public Main() {
        setTitle("Custom Component Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void display() {
        add(new CustomComponent());
        pack();
        // enforces the minimum size of both frame and component
        setMinimumSize(getSize());
        setVisible(true);
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.display();
    }
}

class CustomComponent extends JComponent {

    CustomComponent() {
        setBackground(Color.YELLOW);
    }

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(100, 100);
    }

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

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // paint the BG.
        g.setColor(getBackground());
        g.fillRect(0,0,getWidth(),getHeight());

        int margin = 10;
        Dimension dim = getSize();

        g.setColor(Color.red);
        g.fillRect(margin, margin, dim.width-margin*2, dim.height-margin*2);
    }
}

08-06 06:30