Java-JFrame

Jframe默认是BorderLayout;
JPanel默认是FlowLayout;

下面用简单的Timer Jframe详细介绍JFrame以及进行Timer的简单使用

实现效果展示:
Java-JFrame_第1张图片

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import java.awt.*;
//f.setLayout(new GridLayout(3,2));
public class Java_Timer_Panel extends JFrame implements ActionListener {

    private static final long serialVersionUID = 4603262282860990473L;

    private static final int DEFAULT_WIDTH = 600;
    private static final int DEFAULT_HEIGHT = 400;

    //获取屏幕的分辨率---屏幕的大小
    private static final int width = Toolkit.getDefaultToolkit()
            .getScreenSize().width;
    private static final int height = Toolkit.getDefaultToolkit()
            .getScreenSize().height;

    private Container container;
    private JButton btn;
    private JTextField jtfTime;
    private Timer tmr;

    public Java_Timer_Panel() {
        initComponents();
        Timer tmr = new Timer(1000, this);
        this.tmr = tmr;
        setVisible(true);
    }
    private void initComponents() {
        //this.setLayout(new GridLayout(2,1));         //默认1行,控件占据列
        this.setTitle("秒表");                         //设置窗口标题
        this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);   //设置窗口的大小
        this.setResizable(false);                      //窗口大小不可变化
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit 方法退出应用程序

        this.setLocation((width - DEFAULT_WIDTH) / 2,
                (height - DEFAULT_HEIGHT) / 2);        //设置显示的初始化位置,应该是相对应到左上角的那个点

        jtfTime = new JTextField("嬉戏");             //textfield的初始值设定
        jtfTime.setHorizontalAlignment(JTextField.CENTER); //居中显示
        jtfTime.setFont(new Font("宋体",Font.PLAIN,30));   //设置字体大小
        btn = new JButton("开始倒计时");               //按钮的显示内容的设置

        container = getContentPane();
        JPanel panel = new JPanel();
        //this增加的是整个panel,但是panel需要设置不同的布局方式
        panel.setLayout(new GridLayout(2,1));          //设置的事2行一列

        panel.add(btn);
        panel.add(jtfTime);
        //this的添加控件,必须在该控件本身内部添加控制好之后
        this.add(panel);
        btn.addActionListener(this);
    }
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == btn) {
            jtfTime.setText("10");
            tmr.start();
        } else {
            int t;
            t = Integer.parseInt(jtfTime.getText());
            t--;
            jtfTime.setText("" + t);

            if (t <= 0) {
                tmr.stop();
            }
        }
    }
    public static void main(String[] args) {
        Java_Timer_Panel timeController = new Java_Timer_Panel();
    }

}

你可能感兴趣的:(Java)