JComponent是一个和JPanel很相似的组件的容器,但又有区别。 JPanel不透明,所以在需要透明等应用场景的条件比较麻烦,使用JComponent比较方便。
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); }}复制代码
运行效果: