[Java] code is finishing experiments (multi-threaded, custom exception, interface)

1. The interface file input and output streams +

 

package finalExam;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;


public class FrameAndFile extends JFrame implements ActionListener{
    String default_save_file_name="myTxT.txt";
    
    JTextArea jTextArea;//用户输入框
    JButton jButton_read,jButton_save,jButton_clear;//两个Button
    public FrameAndFile() {
        //界面设置
        setTitle("记事本");
        Container container=getContentPane();
        container.setLayout(newThe BorderLayout ()); 
        the setLocation ( 200,300 ); 
        
        JTextArea = new new the JTextArea (30, 80 ); 
        jTextArea.setLineWrap ( to true ); // activate wrap function 
        jTextArea.setWrapStyleWord ( to true ); // linefeed characters constantly 
        
        Container.add ( " North " , JTextArea); 
        
        the JPanel jPanel_button_area = new new the JPanel ( new new GridLayout (l, 3 )); 
        jButton_read = new new the JButton (" read " ); 
        jButton_clear = new new JButton("清空");
        jButton_save=new JButton("保存");
        jPanel_button_area.add(jButton_save);
        jPanel_button_area.add(jButton_clear);
        jPanel_button_area.add(jButton_read);
        
        jButton_clear.addActionListener(this);
        jButton_read.addActionListener(this);
        jButton_save.addActionListener(this);
        container.add("Center",jPanel_button_area);
        pack();
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
    }
    
    public static void main(String[] args) {
        new FrameAndFile();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()) {
        case "清空":
            jTextArea.setText("");
            break;
        case "保存":
            save();
            break;
        case "读取":
            read();
            break;
        default:
            break;
        }
        
    }
    
    /**
     * 文件读取
     * 使用FileReader+BufferedReader
     * */
    public void read() {
        FileReader fileReader=null;
        BufferedReader bufferedReader=null;
        File file=new File(default_save_file_name);
        if(file.exists()) {
            try {
                fileReader=new FileReader(file);
                bufferedReader=new BufferedReader(fileReader);
                String input_str="";
                while(bufferedReader.ready()) {
                    input_str=input_str+bufferedReader.readLine();
                }
                jTextArea.setText(input_str);
            } catch (FileNotFoundException e) {
                showErrorMessage("出错了:"+e);
                e.printStackTrace();
            } catch (IOException e) {
                showErrorMessage("出错了:"+e);
                e.printStackTrace();
            }finally {
                try {
                    bufferedReader.close();
                    fileReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }else {
            showErrorMessage("文件不存在!");
        }
        
    }
    /**
     * 文件保存
     * 使用FileWriter
     * */
    public void save() {
        Writer writer=null;
        File file=new File(default_save_file_name);
        try {
            writer=new FileWriter(file,true);
            String string=jTextArea.getText();
            if(string!=null||!string.equals("")){
                writer.write(string);
                writer.flush();
                showMessage("保存成功");
            }else {
                showErrorMessage("请输入完整!");
            }
            
        } catch (IOException e) {
            showErrorMessage("出错了:"+e);
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
    public void showMessage(String message) {
        JOptionPane.showMessageDialog(null, message);
    }
    public void showErrorMessage(String message) {
        JOptionPane.showMessageDialog(null, message, "警告",
                JOptionPane.WARNING_MESSAGE);
    }
    
}

 

 

 2 .. write random selection program, arranged in the form of six labels, displays a number between 0-9 on each label, each with a digital thread control their changes, click the "Stop" button all tags stops changing. (Multithreading)

package finalExam;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public classMultiplyThread the extends the JFrame {
     // custom class, encapsulation operation is responsible for all control 
    RandomPanelManager randomPanelManager;
     // main class interface operation is only responsible for 
    public MultiplyThread () { 
        setTitle ( "pumping number" ); 
        Container Container = the getContentPane (); 
        Container. setLayout ( new new the FlowLayout ()); 
        the setBounds ( 200,300,300,350 ); 
        
        randomPanelManager = new new RandomPanelManager (); 
        Container.add (randomPanelManager.getCom ()); 

        setVisible ( to true );
        setDefaultCloseOperation (EXIT_ON_CLOSE); 
        
    } 
    
    
    // management class 
    class RandomPanelManager the implements the ActionListener { 
        List <Mylable> Lables; // used to store six Mylable 
        JPanel JPanel; // enclosed in a large JPanel in 
        public RandomPanelManager () { 
            Lables = new new the ArrayList <MultiplyThread.MyLable> (); 
            JPanel = new new the JPanel ( new new GridLayout (7,1,10,10 ));
             for ( int I = 0; I <. 6; I ++ ) { 
                Mylable Mylable = new new Mylable ();
                lables.add(myLable);
                jPanel.add(myLable);
            }
            JPanel jPanel_buttonJPanel=new JPanel(new GridLayout(1,2));
            JButton jButton_startButton=new JButton("开始");
            JButton jButton_endButton=new JButton("停止");
            jButton_endButton.addActionListener(this);
            jButton_startButton.addActionListener(this);
            jPanel_buttonJPanel.add(jButton_startButton);
            jPanel_buttonJPanel.add(jButton_endButton);
            jPanel.add (jPanel_buttonJPanel); 
        } 
        public the JPanel getCom () {
             return JPanel; 
        } 
        @Override 
        public  void the actionPerformed (the ActionEvent E) {
             Switch (e.getActionCommand ()) {
             Case "Start" : 
                Start (); 
                BREAK ;
             Case " stop " : 
                sTOP (); 
                BREAK ;
             default :
                 BREAK ; 
            }
        } 
        / ** 
         * number at random 
         * attention to the need to first flag is set to true 
         * Create Thread and then placed on the run 
         * * / 
        public  void Start () {
             for (Mylable Item: Lables) { 
                item.init (); 
                Thread Thread = new new Thread (Item); 
                Thread.start (); 
            } 
        } 
        / ** 
         * stop the random number 
         * need only flag is set to false 
         * * / 
        public  void sTOP () {
             for (Mylable Item: Lables) { 
                item.stop (); 
            } 
        } 
    } 
    // custom, implement Runnable
     class Mylable the extends the JPanel the implements Runnable { 
        the JLabel jLabel_tag; 
        Boolean In Flag = to true ;
         public Mylable () { 
            jLabel_tag = new new the JLabel ( "0" );
             the this .setLayout ( new new the FlowLayout ());
             the this .add (jLabel_tag); 
        } 
        
        public  void the setText () { 
            jLabel_tag.setText (getRandomNum () + "" ); 
        } 
        / ** 
         * Get the random number 
         * seed: the current time
         * 范围[0-9]
         * * / 
        Public  int getRandomNum () { 
            a Date DATE = new new a Date (); 
            the Random Random = new new the Random (date.getTime ()); // random seed 
            return random.nextInt (10 ); 
        } 

        @Override 
        public  void RUN () {
             the while (in Flag) { 
                the setText (); 
            } 
        } 
        public  void STOP () { 
            in Flag = to false ; 
        } 
        / ** 
         * recovery, taking into account the repeated execution 
         * * / 
        public  void the init () { 
            In Flag = to true ; 
        } 
    } 
    


    public  static  void main (String [] args) {
         new new MultiplyThread (); 
    } 
}

 

3. a positive integer from exception handling keyboard input, it is determined whether or not an even number, not an exception is thrown

package finalExam;

import java.util.Scanner;
import java.util.regex.Pattern;

public class MyException extends RuntimeException {
    
    private static final long serialVersionUID = 123456789L;

        public MyException() {
        super();
        // TODO Auto-generated constructor stub
    }


    public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }


    public MyException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }


    public MyException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }


    public MyException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }
    
    public static voidmain (String [] args) { 
        Scanner Scanner = null ;
         the try { 
            System.out.println ( "Please enter an integer and continued:" ); 
            Scanner = new new Scanner (the System.in); 
            String inputstr = scanner.nextLine () ;
             IF (that isNumeric (inputstr)) { 
                integer A = the Integer.parseInt (inputstr);
                 IF (A <0 ) {
                     the throw  new new MyException ( "not a positive integer" ); 
                } 
                IF (!% A 2 = 0 ) {
                    the throw  new new MyException ( "is not even" ); 
                } 
                System.out.println ( "successfully entered!" ); 
            } the else {
                 the throw  new new MyException ( "not an integer" ); 
            } 
            
        } the catch (Exception E) { 
            e.printStackTrace () ; 
        } the finally { 
            scanner.close (); 
        } 
    } 
    / ** 
     * is determined by a positive integer string is 
     * this is considered more I can be directly determined without 
     * Scanner.nextInt used in the main function 
     * If the input is not an integer automatically thrown 
     * * /
    public static boolean isNumeric(String string){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(string).matches();   
    }

}

Guess you like

Origin www.cnblogs.com/robotpaul/p/12104935.html