Java程序开发一个窗体有两个按钮,一个是“开始”按钮,一个是“结束”按钮,当用户点击“开始”按钮时就在控制台打印一句话,反之则结束打印。

  • Post author:
  • Post category:java


package javase18;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class javase18_2 extends JFrame {
    private static  final long serialVersionUID=1L;
    JPanel panel=new JPanel();  //定义一个窗体按钮容器
    JButton starbutton=new JButton();  //定义开始按钮
    JButton stopbutton2=new JButton();  //定义结束按钮
    MyThread thread=null;
    private boolean isContinue;
    public javase18_2(){
        try{
            jbInit();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private void jbInit() throws Exception {
        //开始按钮功能制作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //窗体操作
        starbutton.setText("开始");
        starbutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                starbutton_actionPerformed(e);
            }
        });
        //结束按钮功能制作
        stopbutton2.setText("结束");
        stopbutton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stopbutton2_actionPerformed(e);
            }
        });
        this.getContentPane().add(panel,BorderLayout.CENTER);
        panel.add(starbutton);
        starbutton.setBounds(36, 105, 82, 30);   //开始按钮位置
        panel.add(stopbutton2);
        stopbutton2.setBounds(160, 108, 100, 31);    //结束按钮位置
    }
    void starbutton_actionPerformed(ActionEvent e) {
        if (thread != null)
            isContinue=false;
        thread = new MyThread();
        thread.start();  //线程开始执行
    }

    void stopbutton2_actionPerformed(ActionEvent e) {
        if (thread != null)
            isContinue=false;
        thread = null;   //线程为空
    }
    public static void main(String[] args) {
        javase18_2 test = new javase18_2();
        test.setBounds(300,300,300, 80);
        test.setVisible(true);
    }

    private class MyThread extends Thread {
        public MyThread() {
            isContinue=true;
        }

        public void run() {
            System.out.println("\n\n");
            while (true && isContinue) {
                try {
                    Thread.sleep(200);   //线程休眠
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("Java打印\t");
            }
        }
    }
}




版权声明:本文为QQ675396947原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。