且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

扩展JPanels的问题

更新时间:2023-12-05 22:32:52

我(我的个人观点)看不出扩展 JComponent JComponent JPanel JLabel ,更多继承与组合,例如

I (my personal view) can't see nothing wrong with extends JComponent as JComponent, JPanel, JLabel, more Inheritance versus composition, for example

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

public class CustomComponent extends JFrame {

    private static final long serialVersionUID = 1L;

    public CustomComponent() {
        setTitle("Custom Component Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new CustomComponents());
        pack();
        setMinimumSize(getSize());// enforces the minimum size of both frame and component
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                CustomComponent main = new CustomComponent();
                //main.display();
            }
        });
    }
}

class CustomComponents extends JComponent {

    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);
    }
}