Java图形化:JComponent组件

JComponent是一个和JPanel很类似的组件的容器,但又有区别。 JPanel不透明,因此在须要透明等应用场景的条件比较麻烦,使用JComponent比较方便。java

package swing;

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

/** * @author: 个人袜子都是洞 * @description: * @path: tourJava-swing-NotHelloWorld * @date: 2019-01-18 22:48 */
public class NotHelloWorld {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFrame frame = new NotHelloWorldFrame();
            frame.setTitle("Not Hello World");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

class NotHelloWorldFrame extends JFrame {
    public NotHelloWorldFrame () {
        add(new NotHelloWorldComponent());
        // 调整窗口大小,要考虑到其组件的首选大小
        pack();
    }
}

/** * JComponent不一样于JPanel,JPanel不透明,JComponent透明 */
class NotHelloWorldComponent extends JComponent {
    public static final int MESSAGE_X = 75;
    public static final int MESSAGE_Y = 100;

    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;

    public void paintComponent (Graphics g) {
        g.drawString("Not a hello world program", MESSAGE_X, MESSAGE_Y);
    }

    public Dimension getPreferredSize () {
        return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }
}
复制代码

运行效果: spa

JComponent容器
相关文章
相关标签/搜索