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);
}
}
複製程式碼
執行效果: