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容器
相關文章
相關標籤/搜索