- import java.awt.*;
- import javax.swing.*;
- public class TestJFrame {
- public static void main(String[] args) {
- MyFrame mf = new MyFrame("我的第一个窗口");
- }
- }
- class MyFrame extends JFrame {
- Container p;
- public MyFrame() {
- }
- public MyFrame(String title) {
- super(title); //设置窗体标题
- p = getContentPane();
- setSize(500, 500); //设置窗体大小
- centerOnScreen(); //窗体在屏幕中间显示
- setIconImage(new ImageIcon("mm.jpg").getImage()); //设置窗体图标
- p.setBackground(new Color(165, 79, 90)); //设置窗体背景色
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //设置关闭按钮操作
- setVisible(true); //设置窗体可见
- }
- public void centerOnScreen() {
- Dimension displaySize = getToolkit().getScreenSize();
- Dimension winSize = getSize();
- int x = (displaySize.width - winSize.width) / 2;
- int y = (displaySize.height - winSize.height) / 2;
- if(x < 0) {
- x = 0;
- }
- if(y < 0) {
- y = 0;
- }
- setLocation(x, y);
- }
- }
有些代码是不需要重复写的……